/// <summary>
        /// Builds the URL complete.
        /// </summary>
        /// <param name="boardSettings">The board settings.</param>
        /// <param name="url">The URL.</param>
        /// <param name="fullUrl">if set to <c>true</c> [full URL].</param>
        /// <returns>
        /// The new URL.
        /// </returns>
        private string BuildUrlComplete(object boardSettings, string url, bool fullUrl)
        {
            var yafBoardSettings = boardSettings.ToType <YafBoardSettings>();

            var yafTab = new TabController().GetTab(yafBoardSettings.DNNPageTab, yafBoardSettings.DNNPortalId, true);

            var domainName = TestableGlobals.Instance.GetDomainName(HttpContext.Current.Request.Url);
            var aliasUrl   = PortalAliasController.GetPortalAliasByTab(yafBoardSettings.DNNPageTab, domainName);
            var alias      = PortalAliasController.Instance.GetPortalAlias(aliasUrl);

            var portalSettings = new PortalSettings(yafTab.PortalID, alias);

            if (portalSettings.ContentLocalizationEnabled)
            {
                yafTab = new TabController().GetTabByCulture(
                    yafBoardSettings.DNNPageTab,
                    yafBoardSettings.DNNPortalId,
                    new LocaleController().GetCurrentLocale(yafBoardSettings.DNNPortalId));
            }

            if (url.IsNotSet())
            {
                return(this.GetBaseUrl(yafBoardSettings, yafTab));
            }

            if (!global::YAF.Classes.Config.EnableURLRewriting)
            {
                if (!fullUrl)
                {
                    return(Globals.ResolveUrl("{0}&{1}".FormatWith(Globals.ApplicationURL(yafTab.TabID), url)));
                }

                var baseUrlMask = yafBoardSettings.BaseUrlMask;

                if (baseUrlMask.EndsWith("/"))
                {
                    baseUrlMask = baseUrlMask.Remove(baseUrlMask.Length - 1);
                }

                return("{0}{1}".FormatWith(
                           baseUrlMask,
                           Globals.ResolveUrl("{0}&{1}".FormatWith(Globals.ApplicationURL(yafTab.TabID), url))));
            }

            var newUrl = new StringBuilder();

            var boardNameOrPageName = UrlRewriteHelper.CleanStringForURL(yafTab.TabName);

            var parser = new SimpleURLParameterParser(url);

            var pageName       = parser["g"];
            var forumPage      = ForumPages.forum;
            var getDescription = false;

            if (pageName.IsSet())
            {
                try
                {
                    forumPage      = pageName.ToEnum <ForumPages>();
                    getDescription = true;
                }
                catch (Exception)
                {
                    getDescription = false;
                }
            }

            if (getDescription)
            {
                string useKey;
                switch (forumPage)
                {
                case ForumPages.topics:
                {
                    useKey = "f";

                    boardNameOrPageName =
                        UrlRewriteHelper.CleanStringForURL(
                            parser["name"].IsSet()
                                        ? parser["name"]
                                        : UrlRewriteHelper.GetForumName(parser[useKey].ToType <int>()));
                }

                break;

                case ForumPages.posts:
                {
                    if (parser["t"].IsSet())
                    {
                        useKey = "t";

                        var topicName = UrlRewriteHelper.GetTopicName(parser[useKey].ToType <int>());

                        if (topicName.EndsWith("-"))
                        {
                            topicName = topicName.Remove(topicName.Length - 1, 1);
                        }

                        boardNameOrPageName = topicName;
                    }
                    else if (parser["m"].IsSet())
                    {
                        useKey = "m";

                        string topicName;

                        try
                        {
                            topicName = UrlRewriteHelper.GetTopicNameFromMessage(parser[useKey].ToType <int>());

                            if (topicName.EndsWith("-"))
                            {
                                topicName = topicName.Remove(topicName.Length - 1, 1);
                            }
                        }
                        catch (Exception)
                        {
                            topicName = parser["g"];
                        }

                        boardNameOrPageName = topicName;
                    }
                }

                break;

                case ForumPages.profile:
                {
                    useKey = "u";

                    boardNameOrPageName =
                        UrlRewriteHelper.CleanStringForURL(
                            parser["name"].IsSet()
                                        ? parser["name"]
                                        : UrlRewriteHelper.GetProfileName(parser[useKey].ToType <int>()));

                    // Redirect the user to the Dnn profile page.

                    /*return
                     *  Globals.UserProfileURL(
                     *      UserController.GetUserByName(yafPortalId, boardNameOrPageName).UserID);*/
                }

                break;

                case ForumPages.forum:
                {
                    if (parser["c"].IsSet())
                    {
                        useKey = "c";
                        boardNameOrPageName = UrlRewriteHelper.GetCategoryName(parser[useKey].ToType <int>());
                    }
                    else if (parser["g"].IsSet())
                    {
                        return("{0}{1}".FormatWith(this.GetBaseUrl(yafBoardSettings, yafTab), boardNameOrPageName));
                    }
                }

                break;
                }
            }

            if (boardNameOrPageName.Equals(yafTab.TabName))
            {
                boardNameOrPageName = string.Empty;
            }

            newUrl.Append(
                FriendlyUrlProvider.Instance()
                .FriendlyUrl(
                    yafTab,
                    "{0}&{1}".FormatWith(Globals.ApplicationURL(yafTab.TabID), parser.CreateQueryString(new[] { "name" })),
                    "{0}.aspx".FormatWith(boardNameOrPageName),
                    portalSettings));

            // add anchor

            /*if (parser.HasAnchor)
             * {
             * newUrl.AppendFormat("#{0}", parser.Anchor);
             * }*/

            var finalUrl = newUrl.ToString();

            if (finalUrl.EndsWith("/"))
            {
                finalUrl = finalUrl.Remove(finalUrl.Length - 1);
            }

            return(finalUrl.Length >= 260
                       ? this.GetStandardUrl(yafTab, url, boardNameOrPageName, portalSettings)
                       : finalUrl);
        }
Example #2
0
        internal override void RewriteUrl(object sender, EventArgs e)
        {
            var app = (HttpApplication)sender;
            HttpServerUtility server        = app.Server;
            HttpRequest       request       = app.Request;
            HttpResponse      response      = app.Response;
            HttpContext       context       = app.Context;
            string            requestedPath = app.Request.Url.AbsoluteUri;

            if (RewriterUtils.OmitFromRewriteProcessing(request.Url.LocalPath))
            {
                return;
            }

            // 'Carry out first time initialization tasks
            Initialize.Init(app);
            if (!Initialize.ProcessHttpModule(request, false, false))
            {
                return;
            }

            // URL validation
            // check for ".." escape characters commonly used by hackers to traverse the folder tree on the server
            // the application should always use the exact relative location of the resource it is requesting
            var strURL             = request.Url.AbsolutePath;
            var strDoubleDecodeURL = server.UrlDecode(server.UrlDecode(request.RawUrl)) ?? string.Empty;

            if (Globals.FileEscapingRegex.Match(strURL).Success || Globals.FileEscapingRegex.Match(strDoubleDecodeURL).Success)
            {
                DotNetNuke.Services.Exceptions.Exceptions.ProcessHttpException(request);
            }

            try
            {
                // fix for ASP.NET canonicalization issues http://support.microsoft.com/?kbid=887459
                if (request.Path.IndexOf("\\", StringComparison.Ordinal) >= 0 || Path.GetFullPath(request.PhysicalPath) != request.PhysicalPath)
                {
                    DotNetNuke.Services.Exceptions.Exceptions.ProcessHttpException(request);
                }
            }
            catch (Exception exc)
            {
                // DNN 5479
                // request.physicalPath throws an exception when the path of the request exceeds 248 chars.
                // example to test: http://localhost/dotnetnuke_2/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/default.aspx
                Logger.Error(exc);
            }

            string domainName;

            this.RewriteUrl(app, out domainName);

            // blank DomainName indicates RewriteUrl couldn't locate a current portal
            // reprocess url for portal alias if auto add is an option
            if (domainName == string.Empty && CanAutoAddPortalAlias())
            {
                domainName = Globals.GetDomainName(app.Request, true);
            }

            // from this point on we are dealing with a "standard" querystring ( ie. http://www.domain.com/default.aspx?tabid=## )
            // if the portal/url was succesfully identified
            int             tabId           = Null.NullInteger;
            int             portalId        = Null.NullInteger;
            string          portalAlias     = null;
            PortalAliasInfo portalAliasInfo = null;
            bool            parsingError    = false;

            // get TabId from querystring ( this is mandatory for maintaining portal context for child portals )
            if (!string.IsNullOrEmpty(request.QueryString["tabid"]))
            {
                if (!int.TryParse(request.QueryString["tabid"], out tabId))
                {
                    tabId        = Null.NullInteger;
                    parsingError = true;
                }
            }

            // get PortalId from querystring ( this is used for host menu options as well as child portal navigation )
            if (!string.IsNullOrEmpty(request.QueryString["portalid"]))
            {
                if (!int.TryParse(request.QueryString["portalid"], out portalId))
                {
                    portalId     = Null.NullInteger;
                    parsingError = true;
                }
            }

            if (parsingError)
            {
                // The tabId or PortalId are incorrectly formatted (potential DOS)
                DotNetNuke.Services.Exceptions.Exceptions.ProcessHttpException(request);
            }

            try
            {
                // alias parameter can be used to switch portals
                if (request.QueryString["alias"] != null)
                {
                    // check if the alias is valid
                    string childAlias = request.QueryString["alias"];
                    if (!Globals.UsePortNumber())
                    {
                        childAlias = childAlias.Replace(":" + request.Url.Port, string.Empty);
                    }

                    if (PortalAliasController.Instance.GetPortalAlias(childAlias) != null)
                    {
                        // check if the domain name contains the alias
                        if (childAlias.IndexOf(domainName, StringComparison.OrdinalIgnoreCase) == -1)
                        {
                            // redirect to the url defined in the alias
                            response.Redirect(Globals.GetPortalDomainName(childAlias, request, true), true);
                        }
                        else // the alias is the same as the current domain
                        {
                            portalAlias = childAlias;
                        }
                    }
                }

                // PortalId identifies a portal when set
                if (portalAlias == null)
                {
                    if (portalId != Null.NullInteger)
                    {
                        portalAlias = PortalAliasController.GetPortalAliasByPortal(portalId, domainName);
                    }
                }

                // TabId uniquely identifies a Portal
                if (portalAlias == null)
                {
                    if (tabId != Null.NullInteger)
                    {
                        // get the alias from the tabid, but only if it is for a tab in that domain
                        portalAlias = PortalAliasController.GetPortalAliasByTab(tabId, domainName);
                        if (string.IsNullOrEmpty(portalAlias))
                        {
                            // if the TabId is not for the correct domain
                            // see if the correct domain can be found and redirect it
                            portalAliasInfo = PortalAliasController.Instance.GetPortalAlias(domainName);
                            if (portalAliasInfo != null && !request.Url.LocalPath.ToLowerInvariant().EndsWith("/linkclick.aspx"))
                            {
                                if (app.Request.Url.AbsoluteUri.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    strURL = "https://" + portalAliasInfo.HTTPAlias.Replace("*.", string.Empty);
                                }
                                else
                                {
                                    strURL = "http://" + portalAliasInfo.HTTPAlias.Replace("*.", string.Empty);
                                }

                                if (strURL.IndexOf(domainName, StringComparison.InvariantCultureIgnoreCase) == -1)
                                {
                                    strURL += app.Request.Url.PathAndQuery;
                                }

                                response.Redirect(strURL, true);
                            }
                        }
                    }
                }

                // else use the domain name
                if (string.IsNullOrEmpty(portalAlias))
                {
                    portalAlias = domainName;
                }

                // using the DomainName above will find that alias that is the domainname portion of the Url
                // ie. dotnetnuke.com will be found even if zzz.dotnetnuke.com was entered on the Url
                portalAliasInfo = PortalAliasController.Instance.GetPortalAlias(portalAlias);
                if (portalAliasInfo != null)
                {
                    portalId = portalAliasInfo.PortalID;
                }

                // if the portalid is not known
                if (portalId == Null.NullInteger)
                {
                    bool autoAddPortalAlias = CanAutoAddPortalAlias();

                    if (!autoAddPortalAlias && !request.Url.LocalPath.EndsWith(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase))
                    {
                        // allows requests for aspx pages in custom folder locations to be processed
                        return;
                    }

                    if (autoAddPortalAlias)
                    {
                        AutoAddAlias(context);
                    }
                }
            }
            catch (ThreadAbortException exc)
            {
                // Do nothing if Thread is being aborted - there are two response.redirect calls in the Try block
                Logger.Debug(exc);
            }
            catch (Exception ex)
            {
                // 500 Error - Redirect to ErrorPage
                Logger.Error(ex);

                strURL = "~/ErrorPage.aspx?status=500&error=" + server.UrlEncode(ex.Message);
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Server.Transfer(strURL);
            }

            if (portalId != -1)
            {
                // load the PortalSettings into current context
                var portalSettings = new PortalSettings(tabId, portalAliasInfo);
                app.Context.Items.Add("PortalSettings", portalSettings);

                // load PortalSettings and HostSettings dictionaries into current context
                // specifically for use in DotNetNuke.Web.Client, which can't reference DotNetNuke.dll to get settings the normal way
                app.Context.Items.Add("PortalSettingsDictionary", PortalController.Instance.GetPortalSettings(portalId));
                app.Context.Items.Add("HostSettingsDictionary", HostController.Instance.GetSettingsDictionary());

                if (portalSettings.PortalAliasMappingMode == PortalSettings.PortalAliasMapping.Redirect &&
                    portalAliasInfo != null && !portalAliasInfo.IsPrimary &&
                    !string.IsNullOrWhiteSpace(portalSettings.DefaultPortalAlias))    // don't redirect if no primary alias is defined
                {
                    // Permanently Redirect
                    response.StatusCode = 301;

                    var redirectAlias = Globals.AddHTTP(portalSettings.DefaultPortalAlias);
                    var checkAlias    = Globals.AddHTTP(portalAliasInfo.HTTPAlias);
                    var redirectUrl   = string.Concat(redirectAlias, request.RawUrl);
                    if (redirectUrl.StartsWith(checkAlias, StringComparison.InvariantCultureIgnoreCase))
                    {
                        redirectUrl = string.Concat(redirectAlias, redirectUrl.Substring(checkAlias.Length));
                    }

                    response.AppendHeader("Location", redirectUrl);
                }

                // manage page URL redirects - that reach here because they bypass the built-in navigation
                // ie Spiders, saved favorites, hand-crafted urls etc
                if (!string.IsNullOrEmpty(portalSettings.ActiveTab.Url) && request.QueryString["ctl"] == null &&
                    request.QueryString["fileticket"] == null)
                {
                    // Target Url
                    string redirectUrl = portalSettings.ActiveTab.FullUrl;
                    if (portalSettings.ActiveTab.PermanentRedirect)
                    {
                        // Permanently Redirect
                        response.StatusCode = 301;
                        response.AppendHeader("Location", redirectUrl);
                    }
                    else
                    {
                        // Normal Redirect
                        response.Redirect(redirectUrl, true);
                    }
                }

                // manage secure connections
                if (request.Url.AbsolutePath.EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase))
                {
                    // request is for a standard page
                    strURL = string.Empty;

                    // if SSL is enabled
                    if (portalSettings.SSLEnabled)
                    {
                        // if page is secure and connection is not secure orelse ssloffload is enabled and server value exists
                        if ((portalSettings.ActiveTab.IsSecure && !request.IsSecureConnection) &&
                            (UrlUtils.IsSslOffloadEnabled(request) == false))
                        {
                            // switch to secure connection
                            strURL = requestedPath.Replace("http://", "https://");
                            strURL = this.FormatDomain(strURL, portalSettings.STDURL, portalSettings.SSLURL);
                        }
                    }

                    // if SSL is enforced
                    if (portalSettings.SSLEnforced)
                    {
                        // if page is not secure and connection is secure
                        if (!portalSettings.ActiveTab.IsSecure && request.IsSecureConnection)
                        {
                            // check if connection has already been forced to secure orelse ssloffload is disabled
                            if (request.QueryString["ssl"] == null)
                            {
                                strURL = requestedPath.Replace("https://", "http://");
                                strURL = this.FormatDomain(strURL, portalSettings.SSLURL, portalSettings.STDURL);
                            }
                        }
                    }

                    // if a protocol switch is necessary
                    if (!string.IsNullOrEmpty(strURL))
                    {
                        if (strURL.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase))
                        {
                            // redirect to secure connection
                            response.RedirectPermanent(strURL);
                        }
                        else

                        // when switching to an unsecure page, use a clientside redirector to avoid the browser security warning
                        {
                            response.Clear();

                            // add a refresh header to the response
                            response.AddHeader("Refresh", "0;URL=" + strURL);

                            // add the clientside javascript redirection script
                            response.Write("<html><head><title></title>");
                            response.Write("<!-- <script language=\"javascript\">window.location.replace(\"" + strURL +
                                           "\")</script> -->");
                            response.Write("</head><body></body></html>");

                            // send the response
                            response.End();
                        }
                    }
                }
            }
            else
            {
                // alias does not exist in database
                // and all attempts to find another have failed
                // this should only happen if the HostPortal does not have any aliases
                // 404 Error - Redirect to ErrorPage
                strURL = "~/ErrorPage.aspx?status=404&error=" + domainName;
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Server.Transfer(strURL);
            }

            if (app.Context.Items["FirstRequest"] != null)
            {
                app.Context.Items.Remove("FirstRequest");

                // Process any messages in the EventQueue for the Application_Start_FirstRequest event
                EventQueueController.ProcessMessages("Application_Start_FirstRequest");
            }
        }
Example #3
0
        /// <summary>
        /// Builds the URL complete.
        /// </summary>
        /// <param name="boardSettings">The board settings.</param>
        /// <param name="url">The URL.</param>
        /// <param name="fullUrl">if set to <c>true</c> [full URL].</param>
        /// <returns>
        /// The new URL.
        /// </returns>
        private static string BuildUrlComplete([NotNull] object boardSettings, [CanBeNull] string url, bool fullUrl)
        {
            CodeContracts.VerifyNotNull(boardSettings);

            var yafBoardSettings = boardSettings.ToType <BoardSettings>();

            var yafTab = new TabController().GetTab(yafBoardSettings.DNNPageTab, yafBoardSettings.DNNPortalId, true);

            var domainName = TestableGlobals.Instance.GetDomainName(HttpContext.Current.Request.Url);
            var aliasUrl   = PortalAliasController.GetPortalAliasByTab(yafBoardSettings.DNNPageTab, domainName);
            var alias      = PortalAliasController.Instance.GetPortalAlias(aliasUrl);

            IPortalSettings portalSettings = new PortalSettings(yafTab.PortalID, alias);

            if (portalSettings.ContentLocalizationEnabled)
            {
                yafTab = new TabController().GetTabByCulture(
                    yafBoardSettings.DNNPageTab,
                    yafBoardSettings.DNNPortalId,
                    new LocaleController().GetCurrentLocale(yafBoardSettings.DNNPortalId));
            }

            if (url.IsNotSet())
            {
                return(GetBaseUrl(yafBoardSettings, yafTab));
            }

            if (!Configuration.Config.EnableURLRewriting)
            {
                if (!fullUrl)
                {
                    return(Globals.ResolveUrl($"{Globals.ApplicationURL(yafTab.TabID)}&{url}"));
                }

                var baseUrlMask = yafBoardSettings.BaseUrlMask;

                if (baseUrlMask.EndsWith("/"))
                {
                    baseUrlMask = baseUrlMask.Remove(baseUrlMask.Length - 1);
                }

                return
                    ($"{baseUrlMask}{Globals.ResolveUrl($"{Globals.ApplicationURL(yafTab.TabID)}&{url}")}");
            }

            var newUrl = new StringBuilder();

            var boardNameOrPageName = UrlRewriteHelper.CleanStringForURL(yafTab.TabName);

            var parser = new SimpleURLParameterParser(url);

            var pageName       = parser["g"];
            var forumPage      = ForumPages.Board;
            var getDescription = false;

            if (pageName.IsSet())
            {
                try
                {
                    forumPage      = pageName.ToEnum <ForumPages>();
                    getDescription = true;
                }
                catch (Exception)
                {
                    getDescription = false;
                }
            }

            if (getDescription)
            {
                switch (forumPage)
                {
                case ForumPages.Topics:
                {
                    boardNameOrPageName = UrlRewriteHelper.CleanStringForURL(parser["name"]);
                }

                break;

                case ForumPages.Posts:
                {
                    if (parser["t"].IsSet())
                    {
                        var topicName = UrlRewriteHelper.CleanStringForURL(parser["name"]);

                        if (topicName.EndsWith("-"))
                        {
                            topicName = topicName.Remove(topicName.Length - 1, 1);
                        }

                        boardNameOrPageName = topicName;
                    }
                    else if (parser["m"].IsSet())
                    {
                        string topicName;

                        try
                        {
                            topicName = UrlRewriteHelper.CleanStringForURL(parser["name"]);

                            if (topicName.EndsWith("-"))
                            {
                                topicName = topicName.Remove(topicName.Length - 1, 1);
                            }
                        }
                        catch (Exception)
                        {
                            topicName = parser["g"];
                        }

                        boardNameOrPageName = topicName;
                    }
                }

                break;

                case ForumPages.UserProfile:
                {
                    var userInfo = UserController.GetUserByName(parser["name"]);

                    if (userInfo != null)
                    {
                        return(Globals.UserProfileURL(userInfo.UserID));
                    }

                    var userId = BoardContext.Current.Get <IAspNetUsersHelper>()
                                 .GetUserProviderKeyFromUserID(parser["u"].ToType <int>()).ToType <int>();

                    return(Globals.UserProfileURL(userId));
                }

                case ForumPages.Board:
                {
                    if (parser["c"].IsSet())
                    {
                        boardNameOrPageName = UrlRewriteHelper.CleanStringForURL(parser["name"]);
                    }
                    else if (parser["g"].IsSet())
                    {
                        return(yafTab.FullUrl);
                    }
                }

                break;
                }
            }

            if (boardNameOrPageName.Equals(yafTab.TabName))
            {
                boardNameOrPageName = string.Empty;
            }

            newUrl.Append(
                FriendlyUrlProvider.Instance()
                .FriendlyUrl(
                    yafTab,
                    $"{Globals.ApplicationURL(yafTab.TabID)}&{parser.CreateQueryString(new[] { "name" })}",
                    $"{boardNameOrPageName}.aspx",
                    portalSettings));

            // add anchor

            /*if (parser.HasAnchor)
             * {
             * newUrl.AppendFormat("#{0}", parser.Anchor);
             * }*/

            var finalUrl = newUrl.ToString();

            if (finalUrl.EndsWith("/"))
            {
                finalUrl = finalUrl.Remove(finalUrl.Length - 1);
            }

            finalUrl = finalUrl.Replace("/%20/", "-");

            return(finalUrl.Length >= 260
                       ? GetStandardUrl(yafTab, url, boardNameOrPageName, portalSettings)
                       : finalUrl);
        }