Esempio n. 1
0
        /// <summary>
        /// Replace all non-alphanumeric characters with hyphens, ignoring slashes
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private static string Normalize(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return(path);
            }

            // Decode the path.
            path = WebUtility.HtmlDecode(path);
            path = MainUtil.DecodeName(path);

            var segments = path.Split(Constants.UrlSeparator, StringSplitOptions.RemoveEmptyEntries);
            var name     = segments?.Length != 0 ? segments.Last() : null;

            if (!string.IsNullOrEmpty(name))
            {
                var replaced = ItemUtil.ProposeValidItemName(name).ToLower();
                path = path.Replace(name, replaced);
            }

            // Replace characters that Sitecore doesn't allow and lower case the rest.
            path = path.Replace(Constants.Blank, Constants.Hyphen);

            return(path);
        }
        public override void Process(HttpRequestArgs args)
        {
            if (Context.Item != null || args.Url.FilePath.StartsWith("/sitecore") || args.LocalPath.StartsWith("/sitecore"))
            {
                return;
            }

            var requestUrl = args.Url.ItemPath;

            if (requestUrl.Length > 1 && requestUrl.EndsWith("/"))
            {
                requestUrl = requestUrl.Substring(0, requestUrl.Length - 1);
            }
            // remove last element from path and see if resulting path is a bucket
            var index = requestUrl.LastIndexOf('/');

            if (index <= 0)
            {
                return;
            }

            // take the front of the url, looking for /bucket-name
            var bucketPath = MainUtil.DecodeName(requestUrl.Substring(0, index));
            var bucketItem = args.GetItem(bucketPath);

            // was the item a bucket?
            if (bucketItem == null || !BucketManager.IsBucket(bucketItem))
            {
                return;
            }

            // get the name of the item ion the bucket
            var itemName = requestUrl.Substring(index + 1);

            // locate item in bucket by name
            using (var searchContext = ContentSearchManager.GetIndex(Context.Site.GetIndexName()).CreateSearchContext())
            {
                // this returns the First matching item found.  If user has added several
                // items of the same name into the bucket it may return the wrong item.
                var result = searchContext.GetQueryable <BucketItemSearchResult>()
                             .Where(x => x.Name == itemName && x.IsLatestVersion)
                             .Filter(x => x.Paths.Contains(bucketItem.ID));

                var count = result.Count();

                if (count == 0)
                {
                    return;
                }

                if (count > 1)
                {
                    Log.Warn(
                        $"DSP.Foundation.Pipelines.HttpRequestBegin.BucketItemResolver - Process - found {count} items for '{requestUrl}'", this);
                }

                Context.Item = result.First().GetItem();
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Resolves the display name of the using.
        /// </summary>
        /// <param name="itemPath">The item path.</param>
        /// <returns>The resolved item.</returns>
        protected virtual Item ResolveUsingDisplayName(string itemPath)
        {
            Assert.ArgumentNotNull(itemPath, "UrlItemPath");
            using (new SecurityDisabler())
            {
                if (string.IsNullOrEmpty(itemPath) || (itemPath[0] != '/'))
                {
                    return(null);
                }

                int index = itemPath.IndexOf('/', 1);
                if (index < 0)
                {
                    return(null);
                }

                Item root = ItemManager.GetItem(itemPath.Substring(0, index), Language.Current, Sitecore.Data.Version.Latest, Sitecore.Context.Database, SecurityCheck.Disable);
                if (root == null)
                {
                    return(null);
                }

                string path = MainUtil.DecodeName(itemPath.Substring(index));

                Item child = root;
                foreach (string itemName in path.Split(new[] { '/' }))
                {
                    if (itemName.Length == 0)
                    {
                        continue;
                    }

                    child = this.GetChildFromNameOrDisplayName(child, itemName);
                    if (child == null)
                    {
                        return(null);
                    }
                }

                return(child);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Replace all non-alphanumeric characters with hyphens, ignoring slashes
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string Normalize(string path)
        {
            if (path == null)
            {
                return(null);
            }

            // Decode the path.
            path = WebUtility.HtmlDecode(path);
            path = MainUtil.DecodeName(path);

            // Replace characters that we don't allow and lower case the rest.
            string replaced = new string(path.Select(x => char.IsLetterOrDigit(x) || x == '/' || x == '-'
                    ? char.ToLower(x)
                    : '-').ToArray());

            replaced = Undouble(replaced, "-");
            replaced = Undouble(replaced, "/");

            return(replaced);
        }
Esempio n. 5
0
        public override void Process(HttpRequestArgs args)
        {
            try
            {
                if (Context.Item == null)
                {
                    var requestUrl = args.Url.ItemPath;

                    // remove last element from path and see if resulting pathis a bucket
                    var index = requestUrl.LastIndexOf('/');
                    if (index > 0)
                    {
                        var bucketPath = requestUrl.Substring(0, index);
                        var bucketItem = args.GetItem(bucketPath);

                        if (bucketItem != null && BucketManager.IsBucket(bucketItem))
                        {
                            string itemName = requestUrl.Substring(index + 1);
                            if (!string.IsNullOrEmpty(itemName))
                            {
                                itemName = MainUtil.DecodeName(itemName);
                            }
                            // locate item in bucket by name
                            using (var context = ContentSearchManager.GetIndex(Constants.CustomIndex).CreateSearchContext())
                            {
                                var result = context.GetQueryable <SearchResultItem>().Where(x => x.Name == itemName).FirstOrDefault();
                                if (result != null)
                                {
                                    Context.Item = args.GetItem(result.ItemId);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Sitecore.Diagnostics.Log.Error(ex.Message, ex, this);
            }
        }
Esempio n. 6
0
        /// <summary>
        /// checks url for a certain pattern, returns string value if found
        /// Example - www.url.com/blog/category/apples if pattern {0}/category/{1} then returns apples
        /// </summary>
        /// <returns></returns>
        public static string GetUrlValByPattern(string url, string urlPattern)
        {
            char[]   delimiterChars  = { '?' };
            string[] splitUrl        = url.Split(delimiterChars);
            string   decodedItemName = MainUtil.DecodeName(splitUrl[0]);

            try
            {
                string pattern = urlPattern.FormatWith(@"(^.+)", @"(.+)/$");
                Match  match   = Regex.Match(StringUtil.EnsurePostfix('/', decodedItemName), @pattern, RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    return(WebUtility.UrlDecode(match.Groups[2].Value));
                }
            }
            catch (Exception ex)
            {
                Log.Error("XBlog could not resolve url to a blog item", ex, new object());
            }

            return(string.Empty);
        }
    protected virtual Item DoResolveItem(List <string> pathParts, Item root)
    {
        if (!pathParts.Any() || root == null)
        {
            return(root);
        }
        string        str    = pathParts.First();
        List <string> range  = pathParts.GetRange(1, pathParts.Count - 1);
        Item          child1 = GetChild(root, str);
        Item          obj    = DoResolveItem(range, child1);

        if (obj == null)
        {
            string itemName = MainUtil.DecodeName(str);
            if (str != itemName)
            {
                Item child2 = GetChild(root, itemName);
                obj = DoResolveItem(range, child2);
            }
        }
        return(obj);
    }
        private static Item GetParent()
        {
            var url         = System.Web.HttpContext.Current.Request.UrlReferrer;
            var siteContext = Sitecore.Sites.SiteContextFactory.GetSiteContext(url.Host, url.PathAndQuery);

            var homePath = siteContext.StartPath;

            if (!homePath.EndsWith("/"))
            {
                homePath += "/";
            }

            var itemPath = MainUtil.DecodeName(url.AbsolutePath);

            if (itemPath.StartsWith(siteContext.VirtualFolder))
            {
                itemPath = itemPath.Remove(0, siteContext.VirtualFolder.Length);
            }

            var fullPath = homePath + "/" + itemPath;

            return(siteContext.Database.GetItem(fullPath));
        }
Esempio n. 9
0
        /// <summary>
        /// Gets the parent item from item path.
        /// </summary>
        /// <param name="path">The item path.</param>
        /// <returns>The the parent item from item path.</returns>
        protected virtual Item GetParentItemFromItemPath(string path)
        {
            int indexOfSlash = path.LastIndexOf("/");

            path = path.Substring(0, indexOfSlash);

            Item item = Sitecore.Context.Database.GetItem(path);

            if (item == null)
            {
                string path1 = MainUtil.DecodeName(path);
                item = Sitecore.Context.Database.GetItem(path1);
            }

            SiteContext site = Sitecore.Context.Site;
            string      str2 = (site != null) ? site.RootPath : string.Empty;

            if (item == null)
            {
                string path1 = FileUtil.MakePath(str2, path, '/');
                item = Sitecore.Context.Database.GetItem(path1);
            }

            if (item == null)
            {
                string path1 = MainUtil.DecodeName(FileUtil.MakePath(str2, path, '/'));
                item = Sitecore.Context.Database.GetItem(path1);
            }

            if (item == null)
            {
                item = this.ResolveUsingDisplayName(path);
            }

            return(item);
        }
            private static IEnumerable <string> ParseFinalSegment(string segment)
            {
                var r = new Regex(@"(?<start>.*)\/(?<itemname>.*)-(?<datefolders>(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})(?<hour>\d{2})(?<minute>\d{2}))$");

                var matches = r.Matches(segment);

                if (matches.Count > 0)
                {
                    var m = matches[0];
                    yield return(m.Groups["start"].Value);

                    yield return(m.Groups["year"].Value);

                    yield return(m.Groups["month"].Value);

                    yield return(m.Groups["day"].Value);

                    yield return(m.Groups["hour"].Value);

                    yield return(m.Groups["minute"].Value);

                    yield return(MainUtil.DecodeName(m.Groups["itemname"].Value));
                }
            }
Esempio n. 11
0
        /// <summary>
        ///  The main method for the processor.  It simply overrides the Process method.
        /// </summary>
        public override void Process(HttpRequestArgs args)
        {
            // This processer is added to the pipeline after the Sitecore Item Resolver.  We want to skip everything if the item resolved successfully.
            // Also, skip processing for the visitor identification items related to DMS.
            Assert.ArgumentNotNull(args, "args");
            if ((Context.Item == null || AllowRedirectsOnFoundItem(Context.Database)) && args.LocalPath != Constants.Paths.VisitorIdentification && Context.Database != null)
            {
                // Grab the actual requested path for use in both the item and pattern match sections.
                var requestedUrl          = HttpContext.Current.Request.Url.ToString();
                var requestedPath         = HttpContext.Current.Request.Url.AbsolutePath;
                var requestedPathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
                var db = Context.Database;

                // First, we check for exact matches because those take priority over pattern matches.
                if (Sitecore.Configuration.Settings.GetBoolSetting(Constants.Settings.RedirExactMatch, true))
                {
                    // Loop through the exact match entries to look for a match.
                    foreach (Item possibleRedirect in GetRedirects(db, Constants.Templates.RedirectUrl, Constants.Templates.VersionedRedirectUrl, Sitecore.Configuration.Settings.GetSetting(Constants.Settings.QueryExactMatch)))
                    {
                        if (requestedUrl.Equals(possibleRedirect[Constants.Fields.RequestedUrl], StringComparison.OrdinalIgnoreCase) ||
                            requestedPath.Equals(possibleRedirect[Constants.Fields.RequestedUrl], StringComparison.OrdinalIgnoreCase))
                        {
                            var redirectToItem = db.GetItem(ID.Parse(possibleRedirect.Fields[Constants.Fields.RedirectTo]));
                            if (redirectToItem != null)
                            {
                                SendResponse(redirectToItem, HttpContext.Current.Request.Url.Query, args);
                            }
                        }
                    }
                }

                // Second, we check for pattern matches because we didn't hit on an exact match.
                if (Sitecore.Configuration.Settings.GetBoolSetting(Constants.Settings.RedirPatternMatch, true))
                {
                    // Loop through the pattern match items to find a match
                    foreach (Item possibleRedirectPattern in GetRedirects(db, Constants.Templates.RedirectPattern, Constants.Templates.VersionedRedirectPattern, Sitecore.Configuration.Settings.GetSetting(Constants.Settings.QueryExactMatch)))
                    {
                        var redirectPath = string.Empty;
                        if (Regex.IsMatch(requestedUrl, possibleRedirectPattern[Constants.Fields.RequestedExpression], RegexOptions.IgnoreCase))
                        {
                            redirectPath = Regex.Replace(requestedUrl, possibleRedirectPattern[Constants.Fields.RequestedExpression],
                                                         possibleRedirectPattern[Constants.Fields.SourceItem], RegexOptions.IgnoreCase);
                        }
                        else if (Regex.IsMatch(requestedPathAndQuery, possibleRedirectPattern[Constants.Fields.RequestedExpression], RegexOptions.IgnoreCase))
                        {
                            redirectPath = Regex.Replace(requestedPathAndQuery,
                                                         possibleRedirectPattern[Constants.Fields.RequestedExpression],
                                                         possibleRedirectPattern[Constants.Fields.SourceItem], RegexOptions.IgnoreCase);
                        }
                        if (string.IsNullOrEmpty(redirectPath))
                        {
                            continue;
                        }

                        // Query portion gets in the way of getting the sitecore item.
                        var pathAndQuery = redirectPath.Split('?');
                        var path         = pathAndQuery[0];
                        if (LinkManager.Provider != null &&
                            LinkManager.Provider.GetDefaultUrlOptions() != null &&
                            LinkManager.Provider.GetDefaultUrlOptions().EncodeNames)
                        {
                            path = MainUtil.DecodeName(path);
                        }
                        var redirectToItem = db.GetItem(path);
                        if (redirectToItem != null)
                        {
                            var query = pathAndQuery.Length > 1 ? "?" + pathAndQuery[1] : "";
                            SendResponse(redirectToItem, query, args);
                        }
                    }
                }
            }
        }
Esempio n. 12
0
        public override void Process(HttpRequestArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            if (((Context.Item == null) && (Context.Database != null)) && !string.IsNullOrWhiteSpace(args.Url.ItemPath))
            {
                Profiler.StartOperation("Resolve blog item.");
                string qsValue         = string.Empty;
                string decodedItemName = MainUtil.DecodeName(args.Url.ItemPath);

                string         blogItemPath = ResolveBlogItemPath(decodedItemName, XBSettings.XBCategoryUrlPattern, out qsValue);
                BlogFilterType filter       = BlogFilterType.None;
                if (!string.IsNullOrEmpty(blogItemPath))
                {
                    filter = BlogFilterType.Category;
                }
                else
                {
                    blogItemPath = ResolveBlogItemPath(decodedItemName, XBSettings.XBAuthorUrlPattern, out qsValue);
                    if (!string.IsNullOrEmpty(blogItemPath))
                    {
                        filter = BlogFilterType.Author;
                    }
                    else
                    {
                        blogItemPath = ResolveBlogItemPath(decodedItemName, XBSettings.XBTagsUrlPattern, out qsValue);
                        if (!string.IsNullOrEmpty(blogItemPath))
                        {
                            filter = BlogFilterType.Tag;
                        }
                        else
                        {
                            blogItemPath = ResolveBlogItemPath(decodedItemName, XBSettings.XBAuthorViewUrlPattern, out qsValue);
                            if (!string.IsNullOrEmpty(blogItemPath))
                            {
                                filter = BlogFilterType.AuthorView;
                            }
                            else
                            {
                                blogItemPath = ResolveBlogItemPath(decodedItemName, XBSettings.XBSearchURLPattern, out qsValue);
                                if (!string.IsNullOrEmpty(blogItemPath))
                                {
                                    filter = BlogFilterType.Search;
                                }
                            }
                        }
                    }
                }
                if (!string.IsNullOrEmpty(blogItemPath) && filter != BlogFilterType.None)
                {
                    Item blogRoot = args.GetItem(blogItemPath);
                    if (blogRoot != null)
                    {
                        Context.Item = blogRoot;
                        NameValueCollection nv = StringUtil.ParseNameValueCollection(args.Url.QueryString, '&', '=');
                        switch (filter)
                        {
                        case BlogFilterType.Category: nv.Add(XBSettings.XBCategoryQS, qsValue);
                            break;

                        case BlogFilterType.Author: nv.Add(XBSettings.XBAuthorQS, qsValue);
                            break;

                        case BlogFilterType.AuthorView: nv.Add(XBSettings.XBAuthorViewQS, qsValue);
                            break;

                        case BlogFilterType.Tag: nv.Add(XBSettings.XBTagQS, qsValue);
                            break;

                        case BlogFilterType.Search: nv.Add(XBSettings.XBSearchQS, qsValue);
                            break;

                        case BlogFilterType.None:
                        default:
                            break;
                        }
                        args.Url.QueryString = StringUtil.NameValuesToString(nv, "&");
                    }
                }
                Profiler.EndOperation();
            }
        }
        /// <summary>
        ///  The main method for the processor.  It simply overrides the Process method.
        /// </summary>
        public override void Process(HttpRequestArgs args)
        {
            // This processer is added to the pipeline after the Sitecore Item Resolver.  We want to skip everything if the item resolved successfully.
            // Also, skip processing for the visitor identification items related to DMS.
            Assert.ArgumentNotNull(args, "args");
            var allowExternalHost = AllowExternalHost(HttpContext.Current.Request.Url.Host);

            if ((allowExternalHost || Context.Item == null || AllowRedirectsOnFoundItem(Context.Database)) && args.LocalPath != Constants.Paths.VisitorIdentification && Context.Database != null)
            {
                // Grab the actual requested path for use in both the item and pattern match sections.
                var requestedUrl          = HttpContext.Current.Request.Url.ToString().TrimEnd('/');
                var requestedPath         = HttpContext.Current.Request.Url.AbsolutePath;
                var requestedPathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
                var currentIpAddress      = GetClientIPAddress();
                var db = Context.Database;

                // First, we check for exact matches because those take priority over pattern matches.
                if (Sitecore.Configuration.Settings.GetBoolSetting(Constants.Settings.RedirExactMatch, true))
                {
                    // Loop through the exact match entries to look for a match.
                    foreach (Item possibleRedirect in GetRedirects(db, Constants.Templates.RedirectUrl, Constants.Templates.VersionedRedirectUrl, Sitecore.Configuration.Settings.GetSetting(Constants.Settings.QueryExactMatch)))
                    {
                        var trimmedItemRequestedUrl = possibleRedirect[Constants.Fields.RequestedUrl].TrimEnd('/');

                        if (requestedUrl.Equals(trimmedItemRequestedUrl, StringComparison.OrdinalIgnoreCase) ||
                            requestedPath.Equals(trimmedItemRequestedUrl, StringComparison.OrdinalIgnoreCase))
                        {
                            var redirectToItemId = possibleRedirect.Fields[Constants.Fields.RedirectToItem];
                            var redirectToUrl    = possibleRedirect.Fields[Constants.Fields.RedirectToUrl];
                            var redirectFromCode = possibleRedirect.Fields[Constants.Fields.RedirectCode];
                            var maxMind          = Sitecore.Configuration.Settings.GetSetting(Constants.Settings.MaxMindType);

                            if (redirectToItemId.HasValue && !string.IsNullOrEmpty(redirectToItemId.ToString()))
                            {
                                var redirectToItem = db.GetItem(ID.Parse(redirectToItemId));

                                if (redirectToItem != null)
                                {
                                    var responseStatus = GetResponseStatus(possibleRedirect);

                                    switch (maxMind)
                                    {
                                    case "0":
                                    {
                                        SendResponse(redirectToItem, HttpContext.Current.Request.Url.Query, responseStatus, args);
                                        break;
                                    }

                                    case "1":
                                    {
                                        if (!redirectFromCode.HasValue || string.IsNullOrEmpty(redirectFromCode.ToString()))
                                        {
                                            goto case "0";
                                        }

                                        if (redirectFromCode.HasValue && !string.IsNullOrEmpty(redirectFromCode.ToString()) &&
                                            HaveCodeMatch(redirectFromCode.Value, DatabaseHelper.GetCodeFromIP(currentIpAddress)))
                                        {
                                            goto case "0";
                                        }

                                        break;
                                    }

                                    case "2":
                                    {
                                        if (!redirectFromCode.HasValue || string.IsNullOrEmpty(redirectFromCode.ToString()))
                                        {
                                            goto case "0";
                                        }

                                        if (redirectFromCode.HasValue && !string.IsNullOrEmpty(redirectFromCode.ToString()) &&
                                            HaveCodeMatch(redirectFromCode.Value, WebServiceHelper.GetCodeFromIP(currentIpAddress)))
                                        {
                                            goto case "0";
                                        }

                                        break;
                                    }

                                    default:
                                    {
                                        goto case "0";
                                    }
                                    }
                                }
                            }
                            else if (redirectToUrl.HasValue && !string.IsNullOrEmpty(redirectToUrl.ToString()))
                            {
                                var responseStatus = GetResponseStatus(possibleRedirect);

                                switch (maxMind)
                                {
                                case "0":
                                {
                                    SendResponse(redirectToUrl.Value, HttpContext.Current.Request.Url.Query, responseStatus, args);
                                    break;
                                }

                                case "1":
                                {
                                    if (!redirectFromCode.HasValue || string.IsNullOrEmpty(redirectFromCode.ToString()))
                                    {
                                        goto case "0";
                                    }

                                    if (redirectFromCode.HasValue && !string.IsNullOrEmpty(redirectFromCode.ToString()) &&
                                        HaveCodeMatch(redirectFromCode.Value, DatabaseHelper.GetCodeFromIP(currentIpAddress)))
                                    {
                                        goto case "0";
                                    }

                                    break;
                                }

                                case "2":
                                {
                                    if (!redirectFromCode.HasValue || string.IsNullOrEmpty(redirectFromCode.ToString()))
                                    {
                                        goto case "0";
                                    }

                                    if (redirectFromCode.HasValue && !string.IsNullOrEmpty(redirectFromCode.ToString()) &&
                                        HaveCodeMatch(redirectFromCode.Value, DatabaseHelper.GetCodeFromIP(currentIpAddress)))
                                    {
                                        goto case "0";
                                    }

                                    break;
                                }

                                default:
                                {
                                    goto case "0";
                                }
                                }
                            }
                        }
                    }
                }

                // Finally, we check for pattern matches because we didn't hit on an exact match.
                if (Sitecore.Configuration.Settings.GetBoolSetting(Constants.Settings.RedirPatternMatch, true))
                {
                    // Loop through the pattern match items to find a match
                    foreach (Item possibleRedirectPattern in GetRedirects(db, Constants.Templates.RedirectPattern, Constants.Templates.VersionedRedirectPattern, Sitecore.Configuration.Settings.GetSetting(Constants.Settings.QueryExactMatch)))
                    {
                        var redirectPath      = string.Empty;
                        var relativePathMatch = false;

                        if (Regex.IsMatch(requestedUrl, possibleRedirectPattern[Constants.Fields.RequestedExpression],
                                          RegexOptions.IgnoreCase))
                        {
                            redirectPath = Regex.Replace(requestedUrl,
                                                         possibleRedirectPattern[Constants.Fields.RequestedExpression],
                                                         possibleRedirectPattern[Constants.Fields.SourceItem], RegexOptions.IgnoreCase);
                        }
                        else if (Regex.IsMatch(requestedPathAndQuery,
                                               possibleRedirectPattern[Constants.Fields.RequestedExpression], RegexOptions.IgnoreCase))
                        {
                            if (!string.IsNullOrEmpty(possibleRedirectPattern[Constants.Fields.SourceItem]))
                            {
                                redirectPath = Regex.Replace(requestedPathAndQuery,
                                                             possibleRedirectPattern[Constants.Fields.RequestedExpression],
                                                             possibleRedirectPattern[Constants.Fields.SourceItem], RegexOptions.IgnoreCase);
                            }
                            else if (
                                !string.IsNullOrEmpty(
                                    possibleRedirectPattern[Constants.Fields.RelativeDestinationPath]))
                            {
                                redirectPath = Regex.Replace(requestedPathAndQuery,
                                                             possibleRedirectPattern[Constants.Fields.RequestedExpression],
                                                             possibleRedirectPattern[Constants.Fields.RelativeDestinationPath],
                                                             RegexOptions.IgnoreCase);
                                relativePathMatch = true;
                            }
                        }
                        if (string.IsNullOrEmpty(redirectPath))
                        {
                            continue;
                        }

                        // Query portion gets in the way of getting the sitecore item.
                        var pathAndQuery = redirectPath.Split('?');
                        var path         = pathAndQuery[0];
                        if (LinkManager.Provider != null &&
                            LinkManager.Provider.GetDefaultUrlOptions() != null &&
                            LinkManager.Provider.GetDefaultUrlOptions().EncodeNames)
                        {
                            path = MainUtil.DecodeName(path);
                        }
                        var redirectToItem = db.GetItem(path);
                        var responseStatus = GetResponseStatus(redirectToItem);
                        if (redirectToItem != null)
                        {
                            var query = pathAndQuery.Length > 1 ? "?" + pathAndQuery[1] : "";

                            SendResponse(redirectToItem, query, responseStatus, args);
                        }
                        else if (relativePathMatch)
                        {
                            var query = pathAndQuery.Length > 1 ? "?" + pathAndQuery[1] : "";
                            SendResponse(redirectPath, query, responseStatus, args);
                        }
                    }
                }
                if (!allowExternalHost)
                {
                    return;
                }
                //Couldn't find a mapping based on settings. For non-Sitecore hostnames
                var notFoundUrl = Sitecore.Configuration.Settings.GetSetting(Constants.Settings.ExternalHostsNotFoundUrl);
                SendTempResponse(notFoundUrl, HttpContext.Current.Request.Url.Query, args);
            }
        }
Esempio n. 14
0
        public override void Process(HttpRequestArgs args)
        {
            var site = Sitecore.Context.Site.GetMultiSiteContext();

            // only do redirects if no item is found or if request parameters match the configuration settings
            if (ProcessUrl() && Context.Database != null && site != null)
            {
                // Grab the actual requested path for use in both the item and pattern match sections.
                var requestedUrl     = HttpContext.Current.Request.Url.ToString();
                var requestedUrlOnly = requestedUrl.IndexOf("?") > 0 ? requestedUrl.Substring(0, requestedUrl.IndexOf("?")) : requestedUrl;
                requestedUrl = requestedUrl.EndsWith("/") ? requestedUrl.Substring(0, requestedUrl.Length - 1) : requestedUrl;
                var requestedPath         = HttpContext.Current.Request.Url.AbsolutePath;
                var requestedPathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
                var db = Context.Database;

                // In case allowed extensions are defined, only process pipeline when the extension of the request in included in the list
                // of allowed extensions.
                // If the request does not contain an extension, pipeline will always be processed
                if (allowedExtensions != null && allowedExtensions.Count() > 0)
                {
                    var extensionWithDot = Path.GetExtension(requestedPath);
                    if (string.IsNullOrEmpty(extensionWithDot) == false)
                    {
                        if (allowedExtensions.Contains(extensionWithDot.Substring(1).ToLower()) == false)
                        {
                            return;
                        }
                    }
                }

                var ruleFolder = db.GetItem(new Sitecore.Data.ID(site.SiteId)).Children.Where(a => a.DisplayName == "Redirection Rules").FirstOrDefault();

                if (ruleFolder == null)
                {
                    return;
                }

                // Loop through the exact match entries to look for a match.
                foreach (Item possibleRedirect in GetRedirects(ruleFolder, "Redirect Url"))
                {
                    if (possibleRedirect.HasField("Enabled"))
                    {
                        var enabled = ((CheckboxField)possibleRedirect.Fields["Enabled"]).Checked;
                        if (!enabled)
                        {
                            continue;
                        }
                    }

                    bool Is302    = false;
                    bool IsVanity = false;

                    if (possibleRedirect.HasField("Type"))
                    {
                        string type = possibleRedirect["Type"];
                        if (type.StartsWith("302"))
                        {
                            Is302    = true;
                            IsVanity = false;
                        }
                        if (type.ToLower().StartsWith("vanity"))
                        {
                            Is302    = false;
                            IsVanity = true;
                        }
                    }

                    if (requestedUrl.Equals(possibleRedirect["Requested Url"], StringComparison.OrdinalIgnoreCase) ||
                        requestedPath.Equals(possibleRedirect["Requested Url"], StringComparison.OrdinalIgnoreCase) ||
                        requestedUrlOnly.Equals(possibleRedirect["Requested Url"], StringComparison.OrdinalIgnoreCase))
                    {
                        var redirectToItemId = possibleRedirect.Fields["Target Item"];
                        if (redirectToItemId.HasValue && !string.IsNullOrEmpty(redirectToItemId.ToString()))
                        {
                            var redirectToItem = Context.Database.GetItem(ID.Parse(redirectToItemId));
                            var redirectToUrl  = GetRedirectToUrl(redirectToItem);

                            if (possibleRedirect.HasField("Goal") && possibleRedirect.Fields["Goal"].HasValue)
                            {
                                var goal       = ((ReferenceField)possibleRedirect.Fields["Goal"]).TargetItem;
                                var encodedUrl = HttpUtility.UrlEncode(redirectToUrl);
                                redirectToUrl = string.Format("/redirect/{0}?u={1}", goal.ID.ToGuid().ToString("N"), encodedUrl);
                            }

                            if (Is302)
                            {
                                SendTemporaryResponse(redirectToUrl, HttpContext.Current.Request.Url.Query, args);
                            }
                            else if (IsVanity)
                            {
                                SendContent(redirectToUrl, HttpContext.Current.Request.Url.Query, args);
                            }
                            else
                            {
                                //default is 301 permanent
                                SendResponse(redirectToUrl, HttpContext.Current.Request.Url.Query, args);
                            }
                        }
                    }
                }

                // Loop through the pattern match items to find a match
                foreach (Item possibleRedirectPattern in GetRedirects(ruleFolder, "Redirect Pattern"))
                {
                    if (possibleRedirectPattern.HasField("Enabled"))
                    {
                        var enabled = ((CheckboxField)possibleRedirectPattern.Fields["Enabled"]).Checked;
                        if (!enabled)
                        {
                            continue;
                        }
                    }

                    bool Is302    = false;
                    bool IsVanity = false;

                    if (possibleRedirectPattern.HasField("Type"))
                    {
                        string type = possibleRedirectPattern["Type"];
                        if (type.StartsWith("302"))
                        {
                            Is302    = true;
                            IsVanity = false;
                        }
                        if (type.ToLower().StartsWith("vanity"))
                        {
                            Is302    = false;
                            IsVanity = true;
                        }
                    }

                    var redirectPath = string.Empty;
                    if (Regex.IsMatch(requestedUrl, possibleRedirectPattern["Source Expression"], RegexOptions.IgnoreCase))
                    {
                        redirectPath = Regex.Replace(requestedUrl, possibleRedirectPattern["Source Expression"],
                                                     possibleRedirectPattern["Target Expression"], RegexOptions.IgnoreCase);
                    }
                    else if (Regex.IsMatch(requestedPathAndQuery, possibleRedirectPattern["Source Expression"], RegexOptions.IgnoreCase))
                    {
                        redirectPath = Regex.Replace(requestedPathAndQuery,
                                                     possibleRedirectPattern["Source Expression"],
                                                     possibleRedirectPattern["Target Expression"], RegexOptions.IgnoreCase);
                    }
                    if (string.IsNullOrEmpty(redirectPath))
                    {
                        continue;
                    }

                    if (redirectPath.ToLower().StartsWith("/sitecore"))
                    {
                        // Query portion gets in the way of getting the sitecore item.
                        var pathAndQuery = redirectPath.Split(new char[] { '?' }, StringSplitOptions.RemoveEmptyEntries);
                        var path         = pathAndQuery[0];
                        if (LinkManager.GetDefaultUrlOptions() != null &&
                            LinkManager.GetDefaultUrlOptions().EncodeNames)
                        {
                            path = MainUtil.DecodeName(path);
                        }
                        var redirectToItem = db.GetItem(path);
                        if (redirectToItem != null)
                        {
                            var redirectToUrl = GetRedirectToUrl(redirectToItem);

                            if (possibleRedirectPattern.HasField("Goal") && possibleRedirectPattern.Fields["Goal"].HasValue)
                            {
                                var goal = ((ReferenceField)possibleRedirectPattern.Fields["Goal"]).TargetItem;

                                var encodedUrl = HttpUtility.UrlEncode(redirectToUrl);
                                redirectToUrl = string.Format("/redirect/{0}?u={1}", goal.ID.ToGuid().ToString("N"), encodedUrl);
                            }

                            var query = pathAndQuery.Length > 1 ? "?" + pathAndQuery[1] : "";

                            if (Is302)
                            {
                                SendTemporaryResponse(redirectToUrl, query, args);
                            }
                            else if (IsVanity)
                            {
                                SendContent(redirectToUrl, query, args);
                            }
                            else
                            {
                                SendResponse(redirectToUrl, query, args);
                            }
                        }
                    }
                    else
                    {
                        //validate it's a URI
                        Uri outUri = null;
                        if (Uri.TryCreate(redirectPath, UriKind.Absolute, out outUri) &&
                            (outUri.Scheme == Uri.UriSchemeHttp || outUri.Scheme == Uri.UriSchemeHttps))
                        {
                            var redirectToUrl = outUri.GetLeftPart(UriPartial.Path);

                            if (possibleRedirectPattern.HasField("Goal") && possibleRedirectPattern.Fields["Goal"].HasValue)
                            {
                                var goal = ((ReferenceField)possibleRedirectPattern.Fields["Goal"]).TargetItem;

                                var encodedUrl = HttpUtility.UrlEncode(redirectToUrl);
                                redirectToUrl = string.Format("/redirect/{0}?u={1}", goal.ID.ToGuid().ToString("N"), encodedUrl);
                            }

                            var query = outUri.Query;

                            if (Is302)
                            {
                                SendTemporaryResponse(redirectToUrl, query, args);
                            }
                            else if (IsVanity)
                            {
                                SendContent(redirectToUrl, query, args);
                            }
                            else
                            {
                                SendResponse(redirectToUrl, query, args);
                            }
                        }
                    }
                }
            }
        }
        public override void Process(HttpRequestArgs args)
        {
            //don't do backend
            if (Sitecore.Context.Domain.Name.ToLower().Contains("sitecore") || !Sitecore.Context.PageMode.IsNormal)
            {
                return;
            }

            // Get the site context
            SiteContext site = Sitecore.Context.Site;

            // Check if the current user has sufficient rights to enter this page
            if (!SiteManager.CanEnter(site.Name, Sitecore.Context.User))
            {
                return;
            }

            string prefix = args.StartPath;

            if (args.LocalPath.Contains(Sitecore.Context.Site.StartPath))
            {
                prefix = String.Empty;
            }

            if (Sitecore.Context.Database == null)
            {
                return;
            }

            // Get the item using securityDisabler for restricted items such as permission denied items
            Item contextItem = null;

            using (new SecurityDisabler())
            {
                if (Context.Database == null || args.Url.ItemPath.Length == 0)
                {
                    return;
                }

                string path = MainUtil.DecodeName(args.Url.ItemPath);
                Item   item = args.GetItem(path);
                if (item == null)
                {
                    path = args.LocalPath;
                    item = args.GetItem(path);
                }
                if (item == null)
                {
                    path = MainUtil.DecodeName(args.LocalPath);
                    item = args.GetItem(path);
                }
                string str2 = (site != null) ? site.RootPath : string.Empty;
                if (item == null)
                {
                    path = FileUtil.MakePath(str2, args.LocalPath, '/');
                    item = args.GetItem(path);
                }
                if (item == null)
                {
                    path = MainUtil.DecodeName(FileUtil.MakePath(str2, args.LocalPath, '/'));
                    item = args.GetItem(path);
                }
                if (item == null)
                {
                    Item root = ItemManager.GetItem(site.RootPath, Language.Current, Sitecore.Data.Version.Latest, Context.Database, SecurityCheck.Disable);
                    if (root != null)
                    {
                        string path2 = MainUtil.DecodeName(args.LocalPath);
                        item = this.GetSubItem(path2, root);
                    }
                }
                if (item == null)
                {
                    int index = args.Url.ItemPath.IndexOf('/', 1);
                    if (index >= 0)
                    {
                        Item root = ItemManager.GetItem(args.Url.ItemPath.Substring(0, index), Language.Current, Sitecore.Data.Version.Latest, Context.Database, SecurityCheck.Disable);
                        if (root != null)
                        {
                            string path3 = MainUtil.DecodeName(args.Url.ItemPath.Substring(index));
                            item = this.GetSubItem(path3, root);
                        }
                    }
                }
                if (((item == null) && args.UseSiteStartPath) && (site != null))
                {
                    item = args.GetItem(site.StartPath);
                }
                contextItem = item;
            }

            //Item contextItem = Sitecore.Context.Item;
            if (contextItem == null)
            {
                return;
            }

            User u         = Sitecore.Context.User;
            bool isAllowed = AuthorizationManager.IsAllowed(contextItem, AccessRight.ItemRead, u);

            if (isAllowed)
            {
                return;
            }

            string rawURL = HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Request.RawUrl);

            if (site.LoginPage.Length > 0) // Redirect the user
            {
                WebUtil.Redirect(string.Format("{0}?returnUrl={1}", site.LoginPage, rawURL));
            }
        }