Example #1
0
        public static bool TryGetScriptsInDirectory(string root, string path, out ScriptInfo[] scripts)
        {
            // assert: root is not suffixed with directory separator

            // trim leading {root} path:
            if (!string.IsNullOrEmpty(root) && path.StartsWith(root, CurrentPlatform.PathStringComparison))
            {
                if (path.Length == root.Length)
                {
                    path = string.Empty;
                }
                else if (path[root.Length] == CurrentPlatform.DirectorySeparator)
                {
                    path = (path.Length > root.Length + 1) ? path.Substring(root.Length + 1) : string.Empty;
                }
                else
                {
                    scripts = Array.Empty <ScriptInfo>();
                    return(false);
                }
            }

            // try to get compiled scripts within path:
            return(ScriptsMap.TryGetDirectory(path, out scripts));
        }
Example #2
0
        /// <summary>
        /// Resolves path according to PHP semantics, lookups the file in runtime tables and calls its Main method.
        /// </summary>
        /// <param name="cd">Current script directory. Used for relative path resolution. Can be <c>null</c> to not resolve against current directory.</param>
        /// <param name="path">The relative or absolute path to resolve and include.</param>
        /// <param name="locals">Variables scope for the included script.</param>
        /// <param name="this">Reference to <c>this</c> variable.</param>
        /// <param name="self">Reference to current class context.</param>
        /// <param name="once">Whether to include according to include once semantics.</param>
        /// <param name="throwOnError">Whether to include according to require semantics.</param>
        /// <returns>Inclusion result value.</returns>
        public PhpValue Include(string cd, string path, PhpArray locals, object @this = null, RuntimeTypeHandle self = default(RuntimeTypeHandle), bool once = false, bool throwOnError = false)
        {
            ScriptInfo script;

            if (FileSystemUtils.TryGetScheme(path, out var schemespan))
            {
                // SCHEME://SOMETHING
                script = HandleIncludeWithScheme(schemespan, cd, path.Substring(schemespan.Length + 3));
            }
            else
            {
                // regular inclusion resolution
                script = ScriptsMap.ResolveInclude(path, RootPath, IncludePaths, WorkingDirectory, cd);
            }

            if (script.IsValid)
            {
                return((once && _scripts.IsIncluded(script.Index))
                    ? PhpValue.True
                    : script.Evaluate(this, locals, @this, self));
            }
            else
            {
                return(HandleMissingScript(cd, path, throwOnError));
            }
        }
Example #3
0
        /// <summary>
        /// Resolves path according to PHP semantics, lookups the file in runtime tables and calls its Main method.
        /// </summary>
        /// <param name="cd">Current script directory. Used for relative path resolution. Can be <c>null</c> to not resolve against current directory.</param>
        /// <param name="path">The relative or absolute path to resolve and include.</param>
        /// <param name="locals">Variables scope for the included script.</param>
        /// <param name="this">Reference to <c>this</c> variable.</param>
        /// <param name="once">Whether to include according to include once semantics.</param>
        /// <param name="throwOnError">Whether to include according to require semantics.</param>
        /// <returns>Inclusion result value.</returns>
        public PhpValue Include(string cd, string path, PhpArray locals, object @this = null, bool once = false, bool throwOnError = false)
        {
            var script = ScriptsMap.SearchForIncludedFile(path, IncludePaths, cd, _scripts.GetScript);  // TODO: _scripts.GetScript => make relative path from absolute

            if (script.IsValid)
            {
                if (once && _scripts.IsIncluded(script.Index))
                {
                    return(PhpValue.Create(true));
                }
                else
                {
                    return(script.MainMethod(this, locals, @this));
                }
            }
            else
            {
                if (throwOnError)
                {
                    throw new ArgumentException($"File '{path}' cannot be included with current configuration.");   // TODO: ErrCode
                }
                else
                {
                    return(PhpValue.Create(false));   // TODO: Warning
                }
            }
        }
Example #4
0
 protected Context()
 {
     // tables
     _functions = new RoutinesTable();
     _types     = new TypesTable();
     _statics   = new object[StaticIndexes.StaticsCount];
     _constants = ConstsMap.Create(this);
     _scripts   = ScriptsMap.Create();
 }
Example #5
0
            public ConsoleContext(params string[] args)
            {
                _rootPath = ScriptsMap.NormalizeSlashes(Directory.GetCurrentDirectory());

                //
                InitOutput(Console.OpenStandardOutput(), Console.Out);

                // Globals
                InitSuperglobals();
                IntializeArgvArgc(args);
            }
Example #6
0
        /// <summary>
        /// Initializes instance of context.
        /// </summary>
        /// <param name="services">Service provider. Can be <c>null</c> reference to use implicit services.</param>
        protected Context(IServiceProvider services)
        {
            _services = services;

            // tables
            _functions = new RoutinesTable();
            _types     = new TypesTable();
            _statics   = Array.Empty <object>();
            _constants = ConstsMap.Create(this);
            _scripts   = ScriptsMap.Create();
        }
Example #7
0
        public RequestContextAspNet(HttpContext httpcontext)
        {
            Debug.Assert(httpcontext != null);
            Debug.Assert(HttpRuntime.UsingIntegratedPipeline);

            _httpctx  = httpcontext;
            _rootPath = ScriptsMap.NormalizeSlashes(HttpRuntime.AppDomainAppPath).TrimEnd(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });

            this.InitOutput(httpcontext.Response.OutputStream);
            this.InitSuperglobals();

            // TODO: start session if AutoStart is On
        }
Example #8
0
        /// <summary>
        /// Resolves path according to PHP semantics, lookups the file in runtime tables and calls its Main method.
        /// </summary>
        /// <param name="cd">Current script directory. Used for relative path resolution. Can be <c>null</c> to not resolve against current directory.</param>
        /// <param name="path">The relative or absolute path to resolve and include.</param>
        /// <param name="locals">Variables scope for the included script.</param>
        /// <param name="this">Reference to <c>this</c> variable.</param>
        /// <param name="once">Whether to include according to include once semantics.</param>
        /// <param name="throwOnError">Whether to include according to require semantics.</param>
        /// <returns>Inclusion result value.</returns>
        public PhpValue Include(string cd, string path, PhpArray locals, object @this = null, bool once = false, bool throwOnError = false)
        {
            ScriptInfo script;

            path = ScriptsMap.NormalizeSlashes(path);

            if (path.StartsWith(this.RootPath, StringComparison.Ordinal)) // rooted
            {
                script = _scripts.GetScript(path.Substring(this.RootPath.Length + 1));
            }
            else
            {
                script = ScriptsMap.SearchForIncludedFile(path, IncludePaths, cd, _scripts.GetScript);
            }

            if (script.IsValid)
            {
                if (once && _scripts.IsIncluded(script.Index))
                {
                    return(PhpValue.Create(true));
                }
                else
                {
                    return(script.MainMethod(this, locals, @this));
                }
            }
            else
            {
                if (TryIncludeFileContent(path))    // include non-compiled file (we do not allow dynamic compilation)
                {
                    return(PhpValue.Null);
                }
                else
                {
                    var cause = string.Format(Resources.ErrResources.script_not_found, path);

                    PhpException.Throw(
                        throwOnError ? PhpError.Error : PhpError.Notice,
                        Resources.ErrResources.script_inclusion_failed, path, cause, string.Join(";", IncludePaths), cd);

                    if (throwOnError)
                    {
                        throw new ArgumentException(cause);
                    }

                    return(PhpValue.False);
                }
            }
        }
Example #9
0
        /// <summary>
        /// Includes requested script file.
        /// </summary>
        public bool Include(HttpRequest req)
        {
            var relative_path = ScriptsMap.NormalizeSlashes(req.PhysicalPath.Substring(req.PhysicalApplicationPath.Length));
            var script        = ScriptsMap.GetDeclaredScript(relative_path);

            if (script.IsValid)
            {
                this.MainScriptFile = script;
                script.Evaluate(this, this.Globals, null);
                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #10
0
        public RequestContextCore(HttpContext httpcontext, string rootPath, Encoding encoding)
        {
            Debug.Assert(httpcontext != null);
            Debug.Assert(rootPath != null);
            Debug.Assert(rootPath == ScriptsMap.NormalizeSlashes(rootPath));
            Debug.Assert(rootPath.Length != 0 && rootPath[rootPath.Length - 1] != '/');
            Debug.Assert(encoding != null);

            _httpctx  = httpcontext;
            _rootPath = rootPath;
            _encoding = encoding;

            this.InitOutput(httpcontext.Response.Body, new ResponseTextWriter(httpcontext.Response, encoding));
            this.InitSuperglobals();

            // TODO: start session if AutoStart is On
        }
Example #11
0
        public PhpTypeInfo?AutoloadByTypeNameFromClassMap(string fullName, bool onlyAllowed)
        {
            if (fullName == null)
            {
                throw new ArgumentNullException(nameof(fullName));
            }

            if (fullName.Length != 0 && fullName[0] == Utilities.PhpClassName.NamespaceSeparator)
            {
                fullName = fullName.Substring(1);
            }

            if (s_typeMap.TryGetType(fullName, out var tinfo, out var autoload) && tinfo != null)
            {
                if (onlyAllowed && autoload == 0)
                {
                    // type was not marked as to be autoloaded
                    return(null);
                }

                if (autoload == PhpTypeAttribute.AutoloadAllowNoSideEffect)
                {
                    _types.DeclareType(tinfo);
                    return(tinfo);
                }
                else
                {
                    var script = ScriptsMap.GetDeclaredScript(tinfo.RelativePath);

                    // pretend we are PHP and include the script:

                    if (script.IsValid && !_scripts.IsIncluded(script.Index))   // include_once:
                    {
                        script.Evaluate(this, this.Globals, null);

                        return(GetDeclaredType(fullName, autoload: false));
                    }
                }
            }

            return(null);
        }
Example #12
0
        /// <summary>
        /// Implicit autoload mechanism working through CLR reflection.
        /// This ensures when even the caller does not define PHP class autoloading, we allows seamless use of PHP classes and PHP program.
        /// This mechanism gets enabled by default, disabled only when SPL autoload gets initiated (or anything that sets own <see cref="Context.AutoloadService"/>).
        /// </summary>
        PhpTypeInfo ImplicitAutoloadTypeByName(string fullName)
        {
            if (EnableImplicitAutoload)
            {
                var types = s_assClassMap.LookupTypes(fullName);
                if (types != null)
                {
                    ScriptInfo script = default;

                    for (int i = 0; i < types.Length; i++)
                    {
                        var rpath = types[i].RelativePath;
                        if (script.IsValid)
                        {
                            if (script.Path != rpath)
                            {
                                Trace.WriteLine("Type '" + fullName + "' cannot be autoloaded. Ambiguous declarations in " + script.Path + " and " + rpath);
                                return(null); // ambiguity
                            }
                        }
                        else
                        {
                            script = ScriptsMap.GetDeclaredScript(rpath);
                        }
                    }

                    // pretend we are PHP and include the script:

                    if (script.IsValid && !_scripts.IsIncluded(script.Index))   // include_once:
                    {
                        script.Evaluate(this, this.Globals, null, default);

                        return(GetDeclaredType(fullName, autoload: false)); // TODO: can we return types[0] directly in some cases?
                    }
                }
            }

            return(null);
        }
Example #13
0
        /// <summary>
        /// Gets scripts in given directory.
        /// </summary>
        public static bool TryGetScriptsInDirectory(string root, string path, out IEnumerable <ScriptInfo> scripts)
        {
            // trim leading {root} path:
            if (!string.IsNullOrEmpty(root) && path.StartsWith(root, StringComparison.Ordinal))
            {
                if (path.Length == root.Length)
                {
                    path = string.Empty;
                }
                else if (path[root.Length] == CurrentPlatform.DirectorySeparator)
                {
                    path = path.Remove(root.Length + 1);
                }
                else if (root[root.Length - 1] == CurrentPlatform.DirectorySeparator)
                {
                    path = path.Remove(root.Length);
                }
            }

            // try to get compiled scripts within path:
            return(ScriptsMap.TryGetDirectory(path, out scripts));
        }
Example #14
0
        /// <summary>
        /// Resolves path according to PHP semantics, lookups the file in runtime tables and calls its Main method.
        /// </summary>
        /// <param name="cd">Current script directory. Used for relative path resolution. Can be <c>null</c> to not resolve against current directory.</param>
        /// <param name="path">The relative or absolute path to resolve and include.</param>
        /// <param name="locals">Variables scope for the included script.</param>
        /// <param name="this">Reference to <c>this</c> variable.</param>
        /// <param name="self">Reference to current class context.</param>
        /// <param name="once">Whether to include according to include once semantics.</param>
        /// <param name="throwOnError">Whether to include according to require semantics.</param>
        /// <returns>Inclusion result value.</returns>
        public PhpValue Include(string cd, string path, PhpArray locals, object @this = null, RuntimeTypeHandle self = default(RuntimeTypeHandle), bool once = false, bool throwOnError = false)
        {
            var script = ScriptsMap.ResolveInclude(path, RootPath, IncludePaths, WorkingDirectory, cd);

            if (script.IsValid)
            {
                if (once && _scripts.IsIncluded(script.Index))
                {
                    return(PhpValue.Create(true));
                }
                else
                {
                    return(script.Evaluate(this, locals, @this, self));
                }
            }
            else
            {
                if (TryIncludeFileContent(path))    // include non-compiled file (we do not allow dynamic compilation yet)
                {
                    return(PhpValue.Null);
                }
                else
                {
                    var cause = string.Format(Resources.ErrResources.script_not_found, path);

                    PhpException.Throw(
                        throwOnError ? PhpError.Error : PhpError.Notice,
                        Resources.ErrResources.script_inclusion_failed, path, cause, string.Join(";", IncludePaths), cd);

                    if (throwOnError)
                    {
                        throw new ArgumentException(cause);
                    }

                    return(PhpValue.False);
                }
            }
        }
Example #15
0
        /// <summary>
        /// Gets scripts in given directory.
        /// </summary>
        public static bool TryGetScriptsInDirectory(string root, string path, out IEnumerable <ScriptInfo> scripts)
        {
            // trim leading {root} path:
            if (!string.IsNullOrEmpty(root) && path.StartsWith(root, StringComparison.Ordinal)) // TODO: CurrentPlatform comparer
            {
                if (path.Length == root.Length)
                {
                    path = string.Empty;
                }
                else if (path[root.Length] == CurrentPlatform.DirectorySeparator)
                {
                    path = (path.Length > root.Length + 1) ? path.Substring(root.Length + 1) : string.Empty;
                }
                else
                {
                    scripts = Enumerable.Empty <ScriptInfo>();
                    return(false);
                }
            }

            // try to get compiled scripts within path:
            return(ScriptsMap.TryGetDirectory(path, out scripts));
        }
Example #16
0
        /// <summary>
        /// Resolves path according to PHP semantics, lookups the file in runtime tables and calls its Main method.
        /// </summary>
        /// <param name="cd">Current script directory. Used for relative path resolution. Can be <c>null</c> to not resolve against current directory.</param>
        /// <param name="path">The relative or absolute path to resolve and include.</param>
        /// <param name="locals">Variables scope for the included script.</param>
        /// <param name="this">Reference to <c>this</c> variable.</param>
        /// <param name="once">Whether to include according to include once semantics.</param>
        /// <param name="throwOnError">Whether to include according to require semantics.</param>
        /// <returns>Inclusion result value.</returns>
        public PhpValue Include(string cd, string path, PhpArray locals, object @this = null, bool once = false, bool throwOnError = false)
        {
            ScriptInfo script;

            path = path.Replace('/', '\\');                               // normalize slashes
            if (path.StartsWith(this.RootPath, StringComparison.Ordinal)) // rooted
            {
                script = _scripts.GetScript(path.Substring(this.RootPath.Length));
            }
            else
            {
                script = ScriptsMap.SearchForIncludedFile(path, IncludePaths, cd, _scripts.GetScript);
            }
            if (script.IsValid)
            {
                if (once && _scripts.IsIncluded(script.Index))
                {
                    return(PhpValue.Create(true));
                }
                else
                {
                    return(script.MainMethod(this, locals, @this));
                }
            }
            else
            {
                if (throwOnError)
                {
                    throw new ArgumentException($"File '{path}' cannot be included with current configuration.");   // TODO: ErrCode
                }
                else
                {
                    return(PhpValue.Create(false));   // TODO: Warning
                }
            }
        }
Example #17
0
        public static ScriptInfo ResolveScript(HttpRequest req)
        {
            var script = default(ScriptInfo);
            var path   = req.Path.Value;
            var isfile = path.Last() != '/';

            // trim slashes
            path = ScriptsMap.NormalizeSlashes(ArrayUtils.Trim(path, '/'));

            if (isfile)
            {
                script = ScriptsMap.GetDeclaredScript(path);
            }

            if (!script.IsValid)
            {
                // path/defaultdocument
                path   = (path.Length != 0) ? (path + ('/' + DefaultDocument)) : DefaultDocument;
                script = ScriptsMap.GetDeclaredScript(path);
            }

            //
            return(script);
        }
Example #18
0
        public virtual string[] IncludePaths => null;   // TODO:  => this.Config.FileSystem.IncludePaths

        /// <summary>
        /// Gets full script path in current context.
        /// </summary>
        /// <typeparam name="TScript">Script type.</typeparam>
        /// <returns>Full script path.</returns>
        public string ScriptPath <TScript>() => RootPath + ScriptsMap.GetScript <TScript>().Path;
Example #19
0
        public static ScriptInfo ResolveScript(HttpRequest req)
        {
            var path = req.Path.Value.Replace('/', '\\').Trim('\\');    // TODO: normalized form

            return(ScriptsMap.GetDeclaredScript(path));
        }
Example #20
0
        //static ScriptInfo DefaultDocument
        //{
        //    get
        //    {
        //        if (_lazyDefaultDocument.HasValue)
        //        {
        //            return _lazyDefaultDocument.Value;
        //        }

        //        _lazyDefaultDocument = ScriptsMap.GetDeclaredScript("index.php");
        //        return _lazyDefaultDocument.Value;
        //    }
        //}
        //static ScriptInfo? _lazyDefaultDocument;

        public static ScriptInfo ResolveScript(HttpRequest req)
        {
            var path = req.Path.Value.Trim('\\', '/');    // TODO

            return(ScriptsMap.GetDeclaredScript(path));
        }
Example #21
0
 public static ScriptInfo TryGetDeclaredScript(string relpath) => ScriptsMap.GetDeclaredScript(relpath);
Example #22
0
 public static ScriptInfo TryResolveScript(string root, string path) => ScriptsMap.ResolveInclude(path, root, include_path: null, working_dir: root, script_dir: null);
Example #23
0
 public static void SetIncluded <TScript>(ref ScriptsMap scripts) => ElasticBitArray.SetTrue(ref scripts._included, ScriptIndexHolder <TScript> .Index);
Example #24
0
 public static void DeclareScript(string relpath, MainDelegate main) => ScriptsMap.DeclareScript(relpath, main);
Example #25
0
 /// <summary>
 /// Tries to resolve compiled script according to given path.
 /// </summary>
 public static ScriptInfo TryResolveScript(string root, string path) => ScriptsMap.ResolveInclude(path, root, null, null, null);
Example #26
0
 protected void AutoloadFiles()
 {
     ScriptsMap.AutoloadFiles(this);
 }