Example #1
0
        ///<summary>
        /// Locate Portal takes the current request and locates which portal is being called based on this request.
        /// </summary>
        /// <param name="request">request</param>
        private void LocatePortal(HttpRequest request)
        {
            string          domainName  = Globals.GetDomainName(request, true);
            string          portalAlias = domainName;
            PortalAliasInfo pai         = PortalAliasController.GetPortalAliasInfo(portalAlias);

            if (pai != null)
            {
                PortalId = pai.PortalID;
                PortalSettings ps = Utility.GetPortalSettings(pai.PortalID);
                PortalPath = ps.HomeDirectory;
            }
        }
Example #2
0
 public virtual void ProcessRequest(HttpContext context)
 {
     if ((HttpContext.Current.Items["PortalSettings"] != null))
     {
         portalSettings = (PortalSettings)HttpContext.Current.Items["PortalSettings"];
         portalId       = portalSettings.PortalId;
     }
     else
     {
         PortalAliasInfo objPortalAliasInfo = PortalAliasController.GetPortalAliasInfo(HttpContext.Current.Request.Url.Host);
         portalId       = objPortalAliasInfo.PortalID;
         portalSettings = PortalController.GetCurrentPortalSettings();
     }
     Localization.SetThreadCultures(Localization.GetPageLocale(portalSettings), portalSettings);
     userInfo = HttpContext.Current.Request.IsAuthenticated ? Entities.Users.UserController.GetUserByName(PortalId, HttpContext.Current.User.Identity.Name) : new Entities.Users.UserInfo {
         UserID = -1
     };
 }
        /// <summary>
        /// Determines when to do a redirect.  This is separate to the rewriting process.  The module developer can create any type of Url redirect here, because the entire Url of the original request is passed in.
        /// </summary>
        /// <param name="tabId">Identified TabId, if known.  -1 if no valid tabid identified.</param>
        /// <param name="portalid">Identified portalId.</param>
        /// <param name="httpAlias">Identified httpAlias of the request.</param>
        /// <param name="requestUri">The original requested Url</param>
        /// <param name="queryStringCol">The querystring collection of the original request</param>
        /// <param name="options">The friendly url options that currently apply.</param>
        /// <param name="redirectLocation">Out parameter that shows where to redirect to.</param>
        /// <param name="messages">List of messages for debug purposes.  Add to this list to help debug your module.</param>
        /// <returns>true if 301 redirect is required, false if not.  If true, the redirectLocation value must be a valid fully qualified Url.</returns>
        public override bool CheckForRedirect(int tabId, int portalid, string httpAlias, Uri requestUri, System.Collections.Specialized.NameValueCollection queryStringCol, FriendlyUrlOptions options, out string redirectLocation, ref List <string> messages)
        {
            bool doRedirect = false;

            if (messages == null)
            {
                messages = new List <string>();
            }
            redirectLocation = "";//set blank location
            //compare to known pattern of old Urls
            if (_redirectUrls)
            {
                Regex oldNewsRegex = new Regex(@"(&articleType=(?<type>[^&]+))?((&(?<idname>[a-z]*Id)=(?<id>\d+))|((&month=(?<mm>[\d]{1,2}))?&year=(?<yyyy>[\d]{4})))(&(?<pgname>PageId|CurrentPage)=(?<pg>[\d]+))?", RegexOptions.IgnoreCase);
                Match oldNewsMatch = oldNewsRegex.Match(queryStringCol.ToString());
                if (oldNewsMatch.Success)
                {
                    Group  typeGroup   = oldNewsMatch.Groups["type"];
                    Group  idNameGroup = oldNewsMatch.Groups["idname"];
                    Group  idGroup     = oldNewsMatch.Groups["id"];
                    Group  pageGroup   = oldNewsMatch.Groups["pg"];
                    Group  pgNameGrp   = oldNewsMatch.Groups["pgname"];
                    string msg         = "";
                    string id          = null;
                    string furlKey     = null;
                    string friendlyUrl = null;
                    if (idGroup != null && idGroup.Success)
                    {
                        id = idGroup.Value;
                    }
                    string idType = null;
                    if (typeGroup != null && typeGroup.Success)
                    {
                        idType = typeGroup.Value.ToLower();
                    }
                    else
                    {
                        if (idNameGroup != null && idNameGroup.Success)
                        {
                            //check if it's the 'ID' value
                            if (idNameGroup.Value.ToLower() == "id")
                            {
                                idType = "id";
                            }
                        }
                    }
                    //now look at the idType
                    string pagePath = null;
                    if (pgNameGrp != null && pgNameGrp.Success == true && pageGroup != null && pageGroup.Success)
                    {
                        pagePath = pgNameGrp.Value + "/" + pageGroup.Value;
                    }
                    switch (idType)
                    {
                    case "articleview":
                    case "id":
                        msg = "Identified as old-style news article";
                        //article
                        if (pageGroup != null && pageGroup.Success)
                        {
                            furlKey  = "p" + pageGroup.Value;
                            pagePath = null;     //taking care of page separately
                        }
                        else
                        {
                            int articleId = -1;
                            //only for items that are in the range of allowed article ids
                            if (int.TryParse(id, out articleId))
                            {
                                if (articleId >= this.StartingArticleId)
                                {
                                    furlKey = "a" + id;
                                }
                            }
                        }

                        break;

                    case "categoryview":
                        msg     = "Identified as old-style news category";
                        furlKey = "c" + id;
                        break;

                    case "archiveview":
                        //get the mm and yyyy
                        msg = "Identified as old-style news archive";
                        Group yyyyGrp = oldNewsMatch.Groups["yyyy"];
                        if (yyyyGrp != null && yyyyGrp.Success)
                        {
                            string yyyy  = yyyyGrp.Value;
                            string mm    = null;
                            Group  mmGrp = oldNewsMatch.Groups["mm"];
                            if (mmGrp != null && mmGrp.Success)
                            {
                                mm = mmGrp.Value;
                            }
                            friendlyUrl = yyyy;
                            if (mm != null)
                            {
                                friendlyUrl += "/" + mm;
                            }
                        }
                        break;

                    case "authorview":
                        msg     = "Identified as old-style news author";
                        furlKey = "u" + id;
                        break;
                    }
                    if (furlKey != null)
                    {
                        //now lookup the friendly url index
                        TabUrlOptions urlOptions       = GetTabUrlOptions(tabId);
                        Hashtable     friendlyUrlIndex = UrlController.GetFriendlyUrlIndex(tabId, portalid, this, options, urlOptions);
                        if (friendlyUrlIndex != null && friendlyUrlIndex.ContainsKey(furlKey))
                        {
                            //look up the index for the item if we don't already have a friendly Url
                            friendlyUrl = (string)friendlyUrlIndex[furlKey];
                        }
                    }
                    if (friendlyUrl != null)
                    {
                        //now merge with the friendly url for the selected page
                        PortalAliasInfo alias = PortalAliasController.GetPortalAliasInfo(httpAlias);
                        PortalSettings  ps    = new PortalSettings(tabId, alias);
                        if (pagePath != null)
                        {
                            friendlyUrl += this.EnsureLeadingChar("/", pagePath);
                        }
                        string baseUrl = "";
                        if (_noDnnPagePathTabId == tabId)
                        {
                            baseUrl = requestUri.Scheme + Uri.SchemeDelimiter + httpAlias + this.EnsureLeadingChar("/", friendlyUrl) + options.PageExtension;//put onto http Alias with no page path
                        }
                        else
                        {
                            baseUrl = DotNetNuke.Common.Globals.NavigateURL(tabId, ps, "", friendlyUrl); //add on with page path
                        }
                        if (baseUrl != null)
                        {
                            redirectLocation = baseUrl;
                            doRedirect       = true;
                            msg += ", found friendly url " + friendlyUrl + ", redirecting";
                            messages.Add(msg);
                        }
                    }
                }
            }
            return(doRedirect);
        }
        public void OnBeginRequest(object s, EventArgs e)
        {
            var app           = (HttpApplication)s;
            var server        = app.Server;
            var request       = app.Request;
            var response      = app.Response;
            var requestedPath = app.Request.Url.AbsoluteUri;

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

            //'Carry out first time initialization tasks
            Initialize.Init(app);
            if (request.Url.LocalPath.ToLower().Contains("/install/install.aspx") ||
                request.Url.LocalPath.ToLower().Contains("/install/upgradewizard.aspx") ||
                request.Url.LocalPath.ToLower().Contains("/install/installwizard.aspx") ||
                request.Url.LocalPath.ToLower().Contains("captcha.aspx") ||
                request.Url.LocalPath.ToLower().Contains("scriptresource.axd") ||
                request.Url.LocalPath.ToLower().Contains("webresource.axd") ||
                request.Url.LocalPath.ToLower().Contains("dmxdav.axd")
                )
            {
                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));

            if (Regex.Match(strURL, "[\\\\/]\\.\\.[\\\\/]").Success || Regex.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("\\") >= 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
                DnnLog.Error("RawUrl:" + request.RawUrl + " / Referrer:" + request.UrlReferrer.AbsoluteUri, exc);
            }
#if DEBUG
            var timer = new System.Diagnostics.Stopwatch();
            timer.Start();

            app.Context.Items.Add("UrlRewrite:Timer", timer);
#endif

            String domainName;
            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 == "" && 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

            var             tabId           = Null.NullInteger;
            var             portalId        = Null.NullInteger;
            string          portalAlias     = null;
            PortalAliasInfo portalAliasInfo = null;
            var             parsingError    = false;

            // get TabId from querystring ( this is mandatory for maintaining portal context for child portals )
            if (!string.IsNullOrEmpty(request.QueryString["tabid"]))
            {
                if (!Int32.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 (!Int32.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
                    var childAlias = request.QueryString["alias"];
                    if (!Globals.UsePortNumber())
                    {
                        childAlias = childAlias.Replace(":" + request.Url.Port, "");
                    }

                    if (PortalAliasController.GetPortalAliasInfo(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
                            app.Response.AppendHeader("X-Redirect-Reason", "alias parameter");
                            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.GetPortalAliasInfo(domainName);
                            if (portalAliasInfo != null && !request.Url.LocalPath.ToLower().EndsWith("/linkclick.aspx"))
                            {
                                if (app.Request.Url.AbsoluteUri.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    strURL = "https://" + portalAliasInfo.HTTPAlias.Replace("*.", "");
                                }
                                else
                                {
                                    strURL = "http://" + portalAliasInfo.HTTPAlias.Replace("*.", "");
                                }
                                if (strURL.IndexOf(domainName, StringComparison.InvariantCultureIgnoreCase) == -1)
                                {
                                    strURL += app.Request.Url.PathAndQuery;
                                }
                                app.Response.AppendHeader("X-Redirect-Reason", "not correct domain");
                                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.GetPortalAliasInfo(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)
                    {
                        var portalAliasController = new PortalAliasController();
                        portalId = Host.HostPortalID;
                        //the domain name was not found so try using the host portal's first alias
                        if (portalId > Null.NullInteger)
                        {
                            portalAliasInfo           = new PortalAliasInfo();
                            portalAliasInfo.PortalID  = portalId;
                            portalAliasInfo.HTTPAlias = portalAlias;
                            portalAliasController.AddPortalAlias(portalAliasInfo);
                            app.Response.AppendHeader("X-Redirect-Reason", "auto add portalalis");
                            response.Redirect(app.Request.Url.ToString(), true);
                        }
                    }
                }
            }
            catch (ThreadAbortException exc)
            {
                //Do nothing if Thread is being aborted - there are two response.redirect calls in the Try block
                DnnLog.Debug(exc);
            }
            catch (Exception ex)
            {
                //500 Error - Redirect to ErrorPage
                DnnLog.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.GetPortalSettingsDictionary(portalId));
                app.Context.Items.Add("HostSettingsDictionary", HostController.Instance.GetSettingsDictionary());
#if DNN71
                if (portalSettings.PortalAliasMappingMode == PortalSettings.PortalAliasMapping.Redirect &&
                    portalAliasInfo != null && !portalAliasInfo.IsPrimary && !request.IsLocal)
                {
#else
                if (portalSettings.PortalAliasMappingMode == PortalSettings.PortalAliasMapping.Redirect &&
                    !String.IsNullOrEmpty(portalSettings.DefaultPortalAlias) &&
                    portalAliasInfo != null &&
                    portalAliasInfo.HTTPAlias != portalSettings.DefaultPortalAlias && !request.IsLocal)
                {
#endif

                    //Permanently Redirect
                    response.StatusCode = 301;

                    var redirectAlias = Globals.AddHTTP(portalSettings.DefaultPortalAlias);
                    var checkAlias    = Globals.AddHTTP(portalAliasInfo.HTTPAlias);
                    var redirectUrl   = redirectAlias + request.RawUrl;
                    if (redirectUrl.StartsWith(checkAlias, StringComparison.InvariantCultureIgnoreCase))
                    {
                        redirectUrl = redirectAlias + redirectUrl.Substring(checkAlias.Length);
                    }
                    app.Response.AppendHeader("X-Redirect-Reason", "alias redirect");
                    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
                    var redirectUrl = portalSettings.ActiveTab.FullUrl;
                    app.Response.AppendHeader("X-Redirect-Reason", "page url redirect");
                    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 = "";
                    //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) && (IsSSLOffloadEnabled(request) == false))
                        {
                            //switch to secure connection
                            strURL = requestedPath.Replace("http://", "https://");
                            strURL = 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 = 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
                            app.Response.AppendHeader("X-Redirect-Reason", "redirect to secure");
                            response.Redirect(strURL, true);
                        }
                        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");
            }
#if DEBUG
            app.Response.AddHeader("X-OpenUrlRewriter-OnBeginRequest", timer.Elapsed.TotalMilliseconds.ToString());
#endif
        }
Example #5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        public void OnBeginRequest(Object source, EventArgs e)
        {
            try
            {
                var                   app     = (HttpApplication)source;
                var                   context = app.Context;
                PortalSettings        portalSettings;
                PortalAliasController pac = new PortalAliasController();

                PortalInfo portalInfo;
                //var requestedPath = app.Request.Url.AbsoluteUri;
                PortalAliasInfo objPortalAlias;

                var url = context.Request.RawUrl.Replace("?" + context.Request.QueryString, "").ToLower();

                if (Utils.UseFriendlyUrls && (url.EndsWith(".aspx") || url.EndsWith("/")))
                {
                    var myAlias = DotNetNuke.Common.Globals.GetDomainName(app.Request, true);

                    do
                    {
                        objPortalAlias = PortalAliasController.GetPortalAliasInfo(myAlias);

                        if (objPortalAlias != null)
                        {
                            break;
                        }

                        var slashIndex = myAlias.LastIndexOf('/');
                        myAlias = slashIndex > 1 ? myAlias.Substring(0, slashIndex) : "";
                    } while (myAlias.Length > 0);

                    if (objPortalAlias == null)
                    {
                        //portalSettings = new PortalSettings(Host.HostPortalID);
                        //var portalAlias = app.Request.Url.Host;
                        //objPortalAlias = PortalAliasController.GetPortalAliasInfo(portalAlias);
                        return;
                        //if (Host.HostPortalID > Null.NullInteger)
                        //{
                        //    var portalAliasInfo = new PortalAliasInfo
                        //                              {
                        //                                  PortalID = Host.HostPortalID,
                        //                                  HTTPAlias = portalAlias
                        //                              };
                        //    pac.AddPortalAlias(portalAliasInfo);

                        //objPortalAlias = PortalAliasController.GetPortalAliasInfo(portalAlias);
                        //}
                    }
                    else
                    {
                        portalInfo     = new PortalController().GetPortal(objPortalAlias.PortalID);
                        portalSettings = new PortalSettings(portalInfo.PortalID);
                    }

                    if (portalSettings != null)
                    {
                        portalSettings.PortalAlias = objPortalAlias;

                        Regex questionRegEx;
                        Regex tagRegEx;

                        questionRegEx = new Regex("/" + Utils.GetQuestionUrlName(portalSettings).ToLower() + "/([0-9]+)/(.+)(\\.aspx$|\\.aspx?.+)", RegexOptions.IgnoreCase);
                        tagRegEx      = new Regex("/" + Utils.GetTagUrlName(portalSettings).ToLower() + "/(.+)(\\.aspx$|\\.aspx?.+)", RegexOptions.IgnoreCase);

                        if ((questionRegEx.IsMatch(url.ToLower()) && !questionRegEx.Match(url.ToLower()).Groups[1].Value.Contains("/")) || (tagRegEx.IsMatch(url.ToLower()) && !tagRegEx.Match(url.ToLower()).Groups[1].Value.Contains("/")))
                        {
                            string questionTitle;
                            string tagName;


                            // JS 1/25/12: This check is for removing the .aspx from the question and tags.
                            //             There appears to be conflicts between IIS7.5 installations that need to be address
                            //if (HttpRuntime.UsingIntegratedPipeline)
                            //{
                            //    questionRegEx = new Regex("/Question/([0-9]+)/(.+)", RegexOptions.IgnoreCase);
                            //    tagRegEx = new Regex("/Tag/(.+)", RegexOptions.IgnoreCase);
                            //}
                            //else
                            //{
                            //    questionRegEx = new Regex("/Question/([0-9]+)/(.+)\\.aspx$", RegexOptions.IgnoreCase);
                            //    tagRegEx = new Regex("/Tag/(.+)\\.aspx$", RegexOptions.IgnoreCase);
                            //}

                            var albumCtr = new AlbumController();
                            var tInfo    = Utils.GetTabFromUrl(portalSettings);

                            if (tInfo != null && Utils.IsModuleOnTab(tInfo.TabID))
                            {
                                var    match = questionRegEx.Match(url);
                                String relativePath;
                                if (match.Success)
                                {
                                    var questionId = Int32.Parse(match.Groups[1].Value);
                                    questionTitle = match.Groups[2].Value;
                                    if (tInfo != null)
                                    {
                                        AlbumInfo qInfo = albumCtr.GetAlbum(questionId, portalSettings.PortalId);

                                        if (qInfo != null)
                                        {
                                            if (Utils.CreateFriendlySlug(qInfo.AlbumName).ToLower() == questionTitle.ToLower())
                                            {
                                                relativePath = Links.ViewQuestion(questionId, tInfo.TabID, portalSettings).Replace("http://", "").Replace("https://", "").Replace(objPortalAlias.HTTPAlias.Contains("/") ? objPortalAlias.HTTPAlias.Substring(0, objPortalAlias.HTTPAlias.IndexOf("/")) : objPortalAlias.HTTPAlias, "");

                                                context.RewritePath(relativePath);
                                                return;
                                            }
                                            context.Response.Status           = "301 Moved Permanently";
                                            context.Response.RedirectLocation = Links.ViewQuestion(questionId, qInfo.AlbumName, tInfo, portalSettings);
                                        }
                                    }
                                }

                                match = tagRegEx.Match(url);
                                if (match.Success)
                                {
                                    tagName      = match.Groups[1].Value;
                                    tagName      = tagName.Replace("-", " ");
                                    relativePath = Links.ViewTaggedQuestions(tagName, tInfo.TabID, portalSettings).Replace("http://", "").Replace("https://", "").Replace(objPortalAlias.HTTPAlias.Contains("/") ? objPortalAlias.HTTPAlias.Substring(0, objPortalAlias.HTTPAlias.IndexOf("/")) : objPortalAlias.HTTPAlias, "");

                                    context.RewritePath(relativePath);
                                    return;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
            }
        }
Example #6
0
 public PortalAliasInfo GetPortalAlias(string alias)
 {
     return(PortalAliasController.GetPortalAliasInfo(alias));
 }
Example #7
0
        private void RewriteUrl(HttpApplication app, out string portalAlias)
        {
            HttpRequest  request       = app.Request;
            HttpResponse response      = app.Response;
            string       requestedPath = app.Request.Url.AbsoluteUri;


            portalAlias = "";

            //determine portal alias looking for longest possible match
            String          myAlias = Globals.GetDomainName(app.Request, true);
            PortalAliasInfo objPortalAlias;

            do
            {
                objPortalAlias = PortalAliasController.GetPortalAliasInfo(myAlias);

                if (objPortalAlias != null)
                {
                    portalAlias = myAlias;
                    break;
                }

                int slashIndex = myAlias.LastIndexOf('/');
                if (slashIndex > 1)
                {
                    myAlias = myAlias.Substring(0, slashIndex);
                }
                else
                {
                    myAlias = "";
                }
            } while (myAlias.Length > 0);


            app.Context.Items.Add("UrlRewrite:OriginalUrl", app.Request.Url.AbsoluteUri);

            //Friendly URLs are exposed externally using the following format
            //http://www.domain.com/tabid/###/mid/###/ctl/xxx/default.aspx
            //and processed internally using the following format
            //http://www.domain.com/default.aspx?tabid=###&mid=###&ctl=xxx
            //The system for accomplishing this is based on an extensible Regex rules definition stored in /SiteUrls.config
            string sendTo = "";

            //save and remove the querystring as it gets added back on later
            //path parameter specifications will take precedence over querystring parameters
            string strQueryString = "";

            if ((!String.IsNullOrEmpty(app.Request.Url.Query)))
            {
                strQueryString = request.QueryString.ToString();
                requestedPath  = requestedPath.Replace(app.Request.Url.Query, "");
            }

            //get url rewriting rules
            RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;

            //iterate through list of rules
            int matchIndex = -1;

            for (int ruleIndex = 0; ruleIndex <= rules.Count - 1; ruleIndex++)
            {
                //check for the existence of the LookFor value
                string pattern  = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[ruleIndex].LookFor) + "$";
                Match  objMatch = Regex.Match(requestedPath, pattern, RegexOptions.IgnoreCase);

                //if there is a match
                if ((objMatch.Success))
                {
                    //create a new URL using the SendTo regex value
                    sendTo = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, Regex.Replace(requestedPath, pattern, rules[ruleIndex].SendTo, RegexOptions.IgnoreCase));

                    string parameters = objMatch.Groups[2].Value;
                    //process the parameters
                    if ((parameters.Trim().Length > 0))
                    {
                        //split the value into an array based on "/" ( ie. /tabid/##/ )
                        parameters = parameters.Replace("\\", "/");
                        string[] splitParameters = parameters.Split('/');
                        string   parameterName;
                        string   parameterValue;
                        //icreate a well formed querystring based on the array of parameters
                        for (int parameterIndex = 0; parameterIndex < splitParameters.Length; parameterIndex++)
                        {
                            //ignore the page name
                            if (splitParameters[parameterIndex].IndexOf(".aspx", StringComparison.InvariantCultureIgnoreCase) == -1)
                            {
                                //get parameter name
                                parameterName = splitParameters[parameterIndex].Trim();
                                if (parameterName.Length > 0)
                                {
                                    //add parameter to SendTo if it does not exist already
                                    if (sendTo.IndexOf("?" + parameterName + "=", StringComparison.InvariantCultureIgnoreCase) == -1 &&
                                        sendTo.IndexOf("&" + parameterName + "=", StringComparison.InvariantCultureIgnoreCase) == -1)
                                    {
                                        //get parameter delimiter
                                        string parameterDelimiter;
                                        if (sendTo.IndexOf("?") != -1)
                                        {
                                            parameterDelimiter = "&";
                                        }
                                        else
                                        {
                                            parameterDelimiter = "?";
                                        }
                                        sendTo = sendTo + parameterDelimiter + parameterName;
                                        //get parameter value
                                        parameterValue = "";
                                        if (parameterIndex < splitParameters.Length - 1)
                                        {
                                            parameterIndex += 1;
                                            if (!String.IsNullOrEmpty(splitParameters[parameterIndex].Trim()))
                                            {
                                                parameterValue = splitParameters[parameterIndex].Trim();
                                            }
                                        }
                                        //add the parameter value
                                        if (parameterValue.Length > 0)
                                        {
                                            sendTo = sendTo + "=" + parameterValue;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    matchIndex = ruleIndex;
                    break; //exit as soon as it processes the first match
                }
            }
            if (!String.IsNullOrEmpty(strQueryString))
            {
                //add querystring parameters back to SendTo
                string[] parameters = strQueryString.Split('&');
                string   parameterName;
                //iterate through the array of parameters
                for (int parameterIndex = 0; parameterIndex <= parameters.Length - 1; parameterIndex++)
                {
                    //get parameter name
                    parameterName = parameters[parameterIndex];
                    if (parameterName.IndexOf("=") != -1)
                    {
                        parameterName = parameterName.Substring(0, parameterName.IndexOf("="));
                    }
                    //check if parameter already exists
                    if (sendTo.IndexOf("?" + parameterName + "=", StringComparison.InvariantCultureIgnoreCase) == -1 &&
                        sendTo.IndexOf("&" + parameterName + "=", StringComparison.InvariantCultureIgnoreCase) == -1)
                    {
                        //add parameter to SendTo value
                        if (sendTo.IndexOf("?") != -1)
                        {
                            sendTo = sendTo + "&" + parameters[parameterIndex];
                        }
                        else
                        {
                            sendTo = sendTo + "?" + parameters[parameterIndex];
                        }
                    }
                }
            }

            //if a match was found to the urlrewrite rules
            if (matchIndex != -1)
            {
                if (rules[matchIndex].SendTo.StartsWith("~"))
                {
                    //rewrite the URL for internal processing
                    RewriterUtils.RewriteUrl(app.Context, sendTo);
                }
                else
                {
                    //it is not possible to rewrite the domain portion of the URL so redirect to the new URL
                    response.Redirect(sendTo, true);
                }
            }
            else
            {
                //Try to rewrite by TabPath
                string url;
                if (Globals.UsePortNumber() && ((app.Request.Url.Port != 80 && !app.Request.IsSecureConnection) || (app.Request.Url.Port != 443 && app.Request.IsSecureConnection)))
                {
                    url = app.Request.Url.Host + ":" + app.Request.Url.Port + app.Request.Url.LocalPath;
                }
                else
                {
                    url = app.Request.Url.Host + app.Request.Url.LocalPath;
                }

                if (!String.IsNullOrEmpty(myAlias))
                {
                    if (objPortalAlias != null)
                    {
                        int portalID = objPortalAlias.PortalID;
                        //Identify Tab Name
                        string tabPath = url;
                        if (tabPath.StartsWith(myAlias))
                        {
                            tabPath = url.Remove(0, myAlias.Length);
                        }
                        //Default Page has been Requested
                        if ((tabPath == "/" + Globals.glbDefaultPage.ToLower()))
                        {
                            return;
                        }

                        //Start of patch
                        string cultureCode = string.Empty;

                        Dictionary <string, Locale> dicLocales = LocaleController.Instance.GetLocales(portalID);
                        if (dicLocales.Count > 1)
                        {
                            String[] splitUrl = app.Request.Url.ToString().Split('/');

                            foreach (string culturePart in splitUrl)
                            {
                                if (culturePart.IndexOf("-") > -1)
                                {
                                    foreach (KeyValuePair <string, Locale> key in dicLocales)
                                    {
                                        if (key.Key.ToLower().Equals(culturePart.ToLower()))
                                        {
                                            cultureCode = key.Value.Code;
                                            tabPath     = tabPath.Replace("/" + culturePart, "");
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        // Check to see if the tab exists (if localization is enable, check for the specified culture)
                        int tabID = TabController.GetTabByTabPath(portalID, tabPath.Replace("/", "//").Replace(".aspx", ""), cultureCode);

                        // Check to see if neutral culture tab exists
                        if ((tabID == Null.NullInteger && cultureCode.Length > 0))
                        {
                            tabID = TabController.GetTabByTabPath(portalID, tabPath.Replace("/", "//").Replace(".aspx", ""), "");
                        }
                        //End of patch

                        if ((tabID != Null.NullInteger))
                        {
                            string sendToUrl = "~/" + Globals.glbDefaultPage + "?TabID=" + tabID;
                            if (!cultureCode.Equals(string.Empty))
                            {
                                sendToUrl = sendToUrl + "&language=" + cultureCode;
                            }
                            if ((!String.IsNullOrEmpty(app.Request.Url.Query)))
                            {
                                sendToUrl = sendToUrl + "&" + app.Request.Url.Query.TrimStart('?');
                            }
                            RewriterUtils.RewriteUrl(app.Context, sendToUrl);
                            return;
                        }
                        tabPath = tabPath.ToLower();
                        if ((tabPath.IndexOf('?') != -1))
                        {
                            tabPath = tabPath.Substring(0, tabPath.IndexOf('?'));
                        }

                        //Get the Portal
                        PortalInfo portal       = new PortalController().GetPortal(portalID);
                        var        requestQuery = app.Request.Url.Query;
                        if (!string.IsNullOrEmpty(requestQuery))
                        {
                            requestQuery = Regex.Replace(requestQuery, "&?tabid=\\d+", string.Empty, RegexOptions.IgnoreCase);
                            requestQuery = Regex.Replace(requestQuery, "&?portalid=\\d+", string.Empty, RegexOptions.IgnoreCase);
                            requestQuery = requestQuery.TrimStart('?', '&');
                        }
                        if (tabPath == "/login.aspx")
                        {
                            if (portal.LoginTabId > Null.NullInteger && Globals.ValidateLoginTabID(portal.LoginTabId))
                            {
                                if (!string.IsNullOrEmpty(requestQuery))
                                {
                                    RewriterUtils.RewriteUrl(app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.LoginTabId + "&" + requestQuery);
                                }
                                else
                                {
                                    RewriterUtils.RewriteUrl(app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.LoginTabId);
                                }
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(requestQuery))
                                {
                                    RewriterUtils.RewriteUrl(app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=login&" + requestQuery);
                                }
                                else
                                {
                                    RewriterUtils.RewriteUrl(app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=login");
                                }
                            }
                            return;
                        }
                        if (tabPath == "/register.aspx")
                        {
                            if (portal.RegisterTabId > Null.NullInteger)
                            {
                                if (!string.IsNullOrEmpty(requestQuery))
                                {
                                    RewriterUtils.RewriteUrl(app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.RegisterTabId + "&portalid=" + portalID + "&" + requestQuery);
                                }
                                else
                                {
                                    RewriterUtils.RewriteUrl(app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.RegisterTabId + "&portalid=" + portalID);
                                }
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(requestQuery))
                                {
                                    RewriterUtils.RewriteUrl(app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=Register&" + requestQuery);
                                }
                                else
                                {
                                    RewriterUtils.RewriteUrl(app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=Register");
                                }
                            }
                            return;
                        }
                        if (tabPath == "/terms.aspx")
                        {
                            if (!string.IsNullOrEmpty(requestQuery))
                            {
                                RewriterUtils.RewriteUrl(app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=Terms&" + requestQuery);
                            }
                            else
                            {
                                RewriterUtils.RewriteUrl(app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=Terms");
                            }
                            return;
                        }
                        if (tabPath == "/privacy.aspx")
                        {
                            if (!string.IsNullOrEmpty(requestQuery))
                            {
                                RewriterUtils.RewriteUrl(app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=Privacy&" + requestQuery);
                            }
                            else
                            {
                                RewriterUtils.RewriteUrl(app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=Privacy");
                            }
                            return;
                        }
                        tabPath = tabPath.Replace("/", "//");
                        tabPath = tabPath.Replace(".aspx", "");
                        var           objTabController = new TabController();
                        TabCollection objTabs;
                        if (tabPath.StartsWith("//host"))
                        {
                            objTabs = objTabController.GetTabsByPortal(Null.NullInteger);
                        }
                        else
                        {
                            objTabs = objTabController.GetTabsByPortal(portalID);
                        }
                        foreach (KeyValuePair <int, TabInfo> kvp in objTabs)
                        {
                            if ((kvp.Value.IsDeleted == false && kvp.Value.TabPath.ToLower() == tabPath))
                            {
                                if ((!String.IsNullOrEmpty(app.Request.Url.Query)))
                                {
                                    RewriterUtils.RewriteUrl(app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + kvp.Value.TabID + "&" + app.Request.Url.Query.TrimStart('?'));
                                }
                                else
                                {
                                    RewriterUtils.RewriteUrl(app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + kvp.Value.TabID);
                                }
                                return;
                            }
                        }
                    }
                }
                else
                {
                    //Should always resolve to something
                    //RewriterUtils.RewriteUrl(app.Context, "~/" & glbDefaultPage)
                    return;
                }
            }
        }
Example #8
0
        /// <summary>
        /// Called when [begin request].
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        public void OnBeginRequest(Object source, EventArgs e)
        {
            try
            {
                var app     = (HttpApplication)source;
                var context = app.Context;
                var myAlias = DotNetNuke.Common.Globals.GetDomainName(app.Request, true);

                bool   doRedirect       = false;
                string redirectLocation = ""; //set blank location
                string requestUri       = context.Request.Url.AbsoluteUri;
                string scheme           = context.Request.Url.Scheme;

                //Taken from the BasicUrlRewriter to skip directly
                if (context.Request.Url.LocalPath.ToLower().EndsWith("/install/install.aspx") ||
                    context.Request.Url.LocalPath.ToLower().Contains("/install/upgradewizard.aspx") ||
                    context.Request.Url.LocalPath.ToLower().Contains("/install/installwizard.aspx") ||
                    context.Request.Url.LocalPath.ToLower().EndsWith("captcha.aspx") ||
                    context.Request.Url.LocalPath.ToLower().EndsWith("scriptresource.axd") ||
                    context.Request.Url.LocalPath.ToLower().EndsWith("webresource.axd"))
                {
                    return;
                }

                //Strip down the URL slash by slash to get the PortalAlias
                PortalAliasInfo objPortalAlias;
                do
                {
                    objPortalAlias = PortalAliasController.GetPortalAliasInfo(myAlias);
                    if (objPortalAlias != null)
                    {
                        break;
                    }

                    int slashIndex = myAlias.LastIndexOf('/');
                    myAlias = slashIndex > 1 ? myAlias.Substring(0, slashIndex) : "";
                } while (myAlias.Length > 0);

                string urlWithoutAlias = requestUri.Replace(myAlias, "").Replace(scheme + "://", "");
                if (urlWithoutAlias.StartsWith("/"))
                {
                    urlWithoutAlias = urlWithoutAlias.Substring(1);
                }

                //Check Database / Cache for the key.
                //Redirect if key found.
                int portalId = PortalAliasController.GetPortalAliasInfo(myAlias).PortalID;

                foreach (VanityUrlInfo urlInfo in VanityUrlController.GetVanityURLs(portalId))
                {
                    if (urlInfo.VanityUrl.ToLower() == urlWithoutAlias.ToLower())
                    {
                        if ((urlInfo.ActiveStartDate == null || urlInfo.ActiveStartDate < DateTime.Now) &&
                            (urlInfo.ActiveEndDate == null || urlInfo.ActiveEndDate > DateTime.Now))
                        {
                            doRedirect       = true;
                            redirectLocation = scheme + "://" + myAlias + urlInfo.RedirectUrl;
                            //TODO: Test this. Not sure it actaully works
                            VanityUrlController.UpdateLastAccessedDate(urlInfo, portalId);
                        }

                        break;
                    }
                }

                if (doRedirect)
                {
                    context.Response.Redirect(redirectLocation);
                }
            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
            }
        }