Пример #1
0
		/// <summary>
		/// Writes Core legacy options and their values to XML text stream.
		/// Skips options whose values are the same as default values of Phalanger.
		/// </summary>
		/// <param name="writer">XML writer.</param>
		/// <param name="options">A hashtable containing PHP names and option values. Consumed options are removed from the table.</param>
		/// <param name="writePhpNames">Whether to add "phpName" attribute to option nodes.</param>
		public static void CoreOptionsToXml(XmlTextWriter writer, Hashtable options, bool writePhpNames) // GENERICS: <string,string>
		{
			if (writer == null)
				throw new ArgumentNullException("writer");
			if (options == null)
				throw new ArgumentNullException("options");

			ApplicationConfiguration app = new ApplicationConfiguration();
			GlobalConfiguration global = new GlobalConfiguration();
			LocalConfiguration local = new LocalConfiguration();
			PhpIniXmlWriter ow = new PhpIniXmlWriter(writer, options, writePhpNames);

			ow.StartSection("compiler");
			ow.WriteOption("short_open_tag", "ShortOpenTag", true, app.Compiler.ShortOpenTags);
			ow.WriteOption("asp_tags", "AspTags", false, app.Compiler.AspTags);

			ow.StartSection("variables");
			//ow.WriteOption("zend.ze1_compatibility_mode", "ZendEngineV1Compatible", false, local.Variables.ZendEngineV1Compatible);
			ow.WriteOption("register_globals", "RegisterGlobals", false, global.GlobalVariables.RegisterGlobals);
			ow.WriteOption("register_argc_argv", "RegisterArgcArgv", true, global.GlobalVariables.RegisterArgcArgv);
			ow.WriteOption("register_long_arrays", "RegisterLongArrays", true, global.GlobalVariables.RegisterLongArrays);
			ow.WriteOption("variables_order", "RegisteringOrder", "EGPCS", local.Variables.RegisteringOrder);
			//ow.WriteOption("magic_quotes_gpc", "QuoteGpcVariables", true, global.GlobalVariables.QuoteGpcVariables);
			ow.WriteOption("magic_quotes_runtime", "QuoteRuntimeVariables", false, local.Variables.QuoteRuntimeVariables);
			//ow.WriteOption("magic_quotes_sybase", "QuoteInDbManner", false, local.Variables.QuoteInDbManner);
			ow.WriteOption("unserialize_callback_func", "DeserializationCallback", null, local.Variables.DeserializationCallback);

			ow.StartSection("output-control");
			ow.WriteOption("output_buffering", "OutputBuffering", false, local.OutputControl.OutputBuffering);
			ow.WriteOption("output_handler", "OutputHandler", null, local.OutputControl.OutputHandler);
			ow.WriteOption("implicit_flush", "ImplicitFlush", false, local.OutputControl.ImplicitFlush);
			ow.WriteOption("default_mimetype", "ContentType", "text/html", DefaultMimetype);
			ow.WriteOption("default_charset", "Charset", "", DefaultCharset);

			ow.StartSection("request-control");
			ow.WriteOption("max_execution_time", "ExecutionTimeout", 30, local.RequestControl.ExecutionTimeout);
			ow.WriteOption("ignore_user_abort", "IgnoreUserAbort", false, local.RequestControl.IgnoreUserAbort);

			ow.StartSection("error-control");
			ow.WriteEnumOption("error_reporting", "ReportErrors", (int)PhpErrorSet.AllButStrict, (int)local.ErrorControl.ReportErrors, typeof(PhpError));
			ow.WriteOption("display_errors", "DisplayErrors", true, local.ErrorControl.DisplayErrors);
			ow.WriteOption("html_errors", "HtmlMessages", true, local.ErrorControl.HtmlMessages);
			ow.WriteOption("docref_root", "DocRefRoot", null, local.ErrorControl.DocRefRoot.ToString());
			ow.WriteOption("docref_ext", "DocRefExtension", null, local.ErrorControl.DocRefExtension);
			ow.WriteErrorLog("error_log", null, local.ErrorControl.SysLog, local.ErrorControl.LogFile);
			ow.WriteOption("log_errors", "EnableLogging", false, local.ErrorControl.EnableLogging);
			ow.WriteOption("error_prepend_string", "ErrorPrependString", null, local.ErrorControl.ErrorPrependString);
			ow.WriteOption("error_append_string", "ErrorAppendString", null, local.ErrorControl.ErrorAppendString);

			ow.StartSection("session-control");
			ow.WriteOption("session.auto_start", "AutoStart", false, local.Session.AutoStart);
			ow.WriteOption("session.save_handler", "Handler", "files", local.Session.Handler.Name);

			ow.StartSection("assertion");
			ow.WriteOption("assert.active", "Active", true, local.Assertion.Active);
			ow.WriteOption("assert.warning", "ReportWarning", true, local.Assertion.ReportWarning);
			ow.WriteOption("assert.bail", "Terminate", false, local.Assertion.Terminate);
			ow.WriteOption("assert.quiet_eval", "Quiet", false, local.Assertion.Quiet);
			ow.WriteOption("assert.callback", "Callback", null, local.Assertion.Callback);

			ow.StartSection("safe-mode");
			ow.WriteOption("safe_mode", "Enabled", false, global.SafeMode.Enabled);
			ow.WriteOption("open_basedir", "AllowedPathPrefixes", null, global.SafeMode.GetAllowedPathPrefixesJoin());
			ow.WriteOption("safe_mode_exec_dir", "ExecutionDirectory", null, global.SafeMode.ExecutionDirectory);

			ow.StartSection("posted-files");
			ow.WriteOption("file_uploads", "Accept", true, global.PostedFiles.Accept);
			ow.WriteOption("upload_tmp_dir", "TempPath", null, global.PostedFiles.TempPath);

			ow.StartSection("file-system");
			ow.WriteOption("allow_url_fopen", "AllowUrlFopen", true, local.FileSystem.AllowUrlFopen);
			ow.WriteOption("default_socket_timeout", "DefaultSocketTimeout", 60, local.FileSystem.DefaultSocketTimeout);
			ow.WriteOption("user_agent", "UserAgent", null, local.FileSystem.UserAgent);
			ow.WriteOption("from", "AnonymousFtpPassword", null, local.FileSystem.AnonymousFtpPassword);
			ow.WriteOption("include_path", "IncludePaths", ".", local.FileSystem.IncludePaths);

			ow.WriteEnd();
		}
Пример #2
0
		/// <summary>
		/// Creates a new compiler configuration as a shallow copy of 
		/// the relevant sections of the global configuration record.
		/// </summary>
		/// <param name="app">Application configuration record.</param>
		/// <exception cref="ArgumentNullException"><paramref name="app"/> is a <B>null</B> reference.</exception>
		public CompilerConfiguration(ApplicationConfiguration/*!*/ app)
		{
			if (app == null)
				throw new ArgumentNullException("app");

			this.Compiler = app.Compiler;
			this.Globalization = app.Globalization;
#if !SILVERLIGHT
			this.Paths = app.Paths;
#endif
		}
Пример #3
0
        /// <summary>
        /// Includes a specific script using current configuration.
        /// </summary>
        /// <param name="relativeSourcePath">Source root relative path to the script.</param>
        /// <param name="once">Specifies whether script should be included only once.</param>
        /// <returns>The value returned by the global code of the target script.</returns>
        public object Include(string /*!*/ relativeSourcePath, bool once)
        {
            ApplicationConfiguration app_config = Configuration.Application;

            // searches for file:
            FullPath included_full_path = SearchForIncludedFile(PhpError.Error, relativeSourcePath, FullPath.Empty);

            if (included_full_path.IsEmpty)
            {
                return(false);
            }

            ScriptInfo info;
            bool       already_included = scripts.TryGetValue(included_full_path.ToString(), out info);

            // skips inclusion if script has already been included and inclusion's type is "once":
            if (already_included)
            {
                if (once)
                {
                    return(ScriptModule.SkippedIncludeReturnValue);
                }

                // script type loaded, info cannot be null
            }
            else
            {
                PhpSourceFile included_source_file = new PhpSourceFile(app_config.Compiler.SourceRoot, included_full_path);

                // loads script type:
                info = LoadDynamicScriptType(included_source_file);

                // script not found:
                if (info == null)
                {
                    return(false);
                }

                if (MainScriptFile == null)
                {
                    // the first script becomes the main one:
                    DefineMainScript(info, included_source_file);
                }
                else
                {
                    // adds included file into the script list
                    scripts.Add(included_full_path.ToString(), info);
                }
            }

            Debug.Assert(info != null);

            return(GuardedCall((ScriptInfo scriptInfo) =>
            {
                //return PhpScript.InvokeMainHelper(
                //    (Type)scriptType,
                return scriptInfo.Main(
                    this,
                    null,  // no local variables
                    null,  // no object context
                    null,  // no class context
                    true);
            }, info, true));
        }
Пример #4
0
        /// <summary>
        /// Initializes the script context for a PHP console application.
        /// </summary>
        /// <param name="appContext">Application context.</param>
        /// <param name="mainScript">The main script's type or a <B>null</B> reference for a pure application.</param>
        /// <param name="relativeSourcePath">A path to the main script source file.</param>
        /// <param name="sourceRoot">A source root within which an application has been compiler.</param>
        /// <returns>
        /// A new instance of <see cref="ScriptContext"/> with its own copy of local configuration
        /// to be used by the application.
        /// </returns>
        /// <exception cref="System.Configuration.ConfigurationErrorsException">
        /// Web configuration is invalid. The context is not initialized then.
        /// </exception>
        /// <remarks>
        /// Use this method if you want to initialize application in the same way the PHP console/Windows
        /// application is initialized. The returned script context is initialized as follows:
        /// <list type="bullet">
        ///   <term>The application's source root is set.</term>
        ///   <term>The main script of the application is defined.</term>
        ///   <term>Output and input streams are set to standard output and input, respectively.</term>
        ///   <term>Current culture it set to <see cref="CultureInfo.InvariantCulture"/>.</term>
        ///   <term>Auto-global variables ($_GET, $_SET, etc.) are initialized.</term>
        ///   <term>Working directory is set tothe current working directory.</term>
        /// </list>
        /// </remarks>
        public static ScriptContext /*!*/ InitApplication(ApplicationContext /*!*/ appContext, Type mainScript,
                                                          string relativeSourcePath, string sourceRoot)
        {
            // loads configuration into the given application context
            // (applies only if the config has not been loaded yet by the current thread):
            Configuration.Load(appContext);

            ApplicationConfiguration app_config = Configuration.Application;

            if (mainScript != null)
            {
                if (relativeSourcePath == null)
                {
                    throw new ArgumentNullException("relativeSourcePath");
                }

                if (sourceRoot == null)
                {
                    throw new ArgumentNullException("sourceRoot");
                }

                // overrides source root configuration if not explicitly specified in config file:
                if (!app_config.Compiler.SourceRootSet)
                {
                    app_config.Compiler.SourceRoot = new FullPath(sourceRoot);
                }
            }

            // takes a writable copy of a global configuration:
            LocalConfiguration config = (LocalConfiguration)Configuration.DefaultLocal.DeepCopy();

            // sets invariant culture as a default one:
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            ScriptContext result = new ScriptContext(appContext, config, Console.Out, Console.OpenStandardOutput());

            result.IsOutputBuffered = result.config.OutputControl.OutputBuffering;
            result.AutoGlobals.Initialize(config, null);
            result.WorkingDirectory                 = Directory.GetCurrentDirectory();
            result.ThrowExceptionOnError            = true;
            result.config.ErrorControl.HtmlMessages = false;

            if (mainScript != null)
            {
                // converts relative path of the script source to full canonical path using source root from the configuration:
                PhpSourceFile main_source_file = new PhpSourceFile(
                    app_config.Compiler.SourceRoot,
                    new FullPath(relativeSourcePath, app_config.Compiler.SourceRoot)
                    );

                result.DefineMainScript(new ScriptInfo(mainScript), main_source_file);
            }

            ScriptContext.CurrentContext = result;

            Externals.BeginRequest();
            result.FinallyDispose += Externals.EndRequest;

            //
            return(result);
        }
Пример #5
0
        public static void RunApplication(Delegate /*!*/ mainRoutine, string relativeSourcePath, string sourceRoot)
        {
            bool is_pure = mainRoutine is RoutineDelegate;

            ApplicationContext app_context = ApplicationContext.Default;

            // default culture:
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            // try to preload configuration (to prevent exceptions during InitApplication:
            try
            {
                Configuration.Load(app_context);
            }
            catch (ConfigurationErrorsException e)
            {
                Console.WriteLine(e.Message);
                return;
            }

            ApplicationConfiguration app_config = Configuration.Application;

            if (is_pure && !app_config.Compiler.LanguageFeaturesSet)
            {
                app_config.Compiler.LanguageFeatures = LanguageFeatures.PureModeDefault;
            }

            // environment settings; modifies the PATH variable to fix LoadLibrary called by native extensions:
            if (EnvironmentUtils.IsDotNetFramework)
            {
                string path = Environment.GetEnvironmentVariable("PATH");
                path = String.Concat(path, Path.PathSeparator, app_config.Paths.ExtNatives);

                Environment.SetEnvironmentVariable("PATH", path);
            }

            Type main_script;

            if (is_pure)
            {
                // loads the calling assembly:
                app_context.AssemblyLoader.Load(mainRoutine.Method.Module.Assembly, null);
                main_script = null;
            }
            else
            {
                main_script = mainRoutine.Method.DeclaringType;
                app_context.AssemblyLoader.LoadScriptLibrary(System.Reflection.Assembly.GetEntryAssembly(), ".");
            }

            ScriptContext context = InitApplication(app_context, main_script, relativeSourcePath, sourceRoot);

            try
            {
                context.GuardedCall <object, object>(context.GuardedMain, mainRoutine, true);
                context.GuardedCall <object, object>(context.FinalizeBufferedOutput, null, false);
                context.GuardedCall <object, object>(context.ProcessShutdownCallbacks, null, false);
                context.GuardedCall <object, object>(context.FinalizePhpObjects, null, false);
            }
            finally
            {
                Externals.EndRequest();
            }
        }
Пример #6
0
        public object DynamicInclude(
            string includedFilePath,
            string includerFileRelPath,//TODO: Now it's not relative because RelativePath class doesn't work properly with HTTP addresses
            Dictionary <string, object> variables,
            DObject self,
            DTypeDesc includer,
            InclusionTypes inclusionType)
        {
            ApplicationConfiguration app_config = Configuration.Application;

            // determines inclusion behavior:
            PhpError error_severity = InclusionTypesEnum.IsMustInclusion(inclusionType) ? PhpError.Error : PhpError.Warning;
            bool     once           = InclusionTypesEnum.IsOnceInclusion(inclusionType);


            System.Threading.AutoResetEvent downloadFinished = null;
            string eval = string.Empty;

            downloadFinished = new System.Threading.AutoResetEvent(false);

            WebClient webclient = new WebClient();

            webclient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(
                delegate(object sender, DownloadStringCompletedEventArgs downEventArgs)
            {
                if (downEventArgs.Error == null)
                {
                    eval = downEventArgs.Result;

                    // workaround for Firefox BrowserHttpWebRequest bug -
                    // assuming that we're downloading PHP source starting with '<?'
                    int srcStart = 0;
                    while (!(eval[srcStart] == '<' && eval[srcStart + 1] == '?') && (srcStart + 1 < eval.Length))
                    {
                        srcStart++;
                    }
                    eval = eval.Substring(srcStart);

                    downloadFinished.Set();
                }
            }
                );

            Uri baseUri = new Uri(app_config.Compiler.SourceRoot + "/", UriKind.Absolute);
            Uri uriFile = new Uri(includedFilePath, UriKind.RelativeOrAbsolute);
            Uri uri     = new Uri(baseUri, uriFile);

            webclient.DownloadStringAsync(uri);

            ThreadStart ts = new ThreadStart(() => {
                downloadFinished.WaitOne();

                try
                {
                    DynamicCode.EvalFile(eval, ScriptContext.CurrentContext, variables, self, null, includedFilePath, 0, 0, -1);
                }
                catch (Exception ex)
                {
                    var canvas = ((ClrObject)ScriptContext.CurrentContext.AutoGlobals.Canvas.Value).RealObject as System.Windows.Controls.Canvas;

                    canvas.Dispatcher.BeginInvoke(() =>
                    {
                        throw ex;
                    });
                }
            });

            if (inclusionType == InclusionTypes.RunSilverlight) // new thread have to be created
            {
                new Thread(ts).Start();
            }
            else
            {
                ts(); // just continue on this thread
            }

            return(null);
        }