internal static bool CheckUserProfileReplacement(string newPath,
                                                         TabInfo tab,
                                                         PortalSettings portalSettings,
                                                         FriendlyUrlSettings settings,
                                                         FriendlyUrlOptions options,
                                                         out string changedPath,
                                                         out bool changeToSiteRoot,
                                                         out bool allowOtherParameters,
                                                         ref List <string> meessages,
                                                         Guid parentTraceId)
        {
            if (meessages == null)
            {
                meessages = new List <string>();
            }
            bool urlWasChanged = false;

            //initialise defaults to always return valid items
            changedPath          = newPath;
            changeToSiteRoot     = false;
            allowOtherParameters = true;

            //determine if this url should be converted to a userprofile url by checking the saved rules matching the tab/portalid
            if (portalSettings != null && tab.PortalID == portalSettings.PortalId &&
                (tab.TabID == portalSettings.UserTabId || portalSettings.UserTabId == -1 ||
                 tab.ParentId == portalSettings.UserTabId))        //-1 == all tabs in portal
            {
                int    userId;
                string rawUserId, remainingPath;
                //split the userid and other profile parameters from the friendly url path,
                //and return the userid and remaining parts as separate items
                SplitUserIdFromFriendlyUrlPath(newPath,
                                               "UserId",
                                               "",
                                               out rawUserId,
                                               out remainingPath);
                if (rawUserId != null)
                {
                    meessages.Add("User Profile Url : RawUserId = " + rawUserId + " remainingPath = " + remainingPath);
                }
                else
                {
                    meessages.Add("User Profile Url : RawUserId = " + "null" + " remainingPath = " + remainingPath);
                }

                //the rawuserid is just the string representation of the userid from the path.
                //It should be considered 'untrusted' until cleaned up,
                //converted to an int and checked against the database
                if (!String.IsNullOrEmpty(rawUserId) && Int32.TryParse(rawUserId, out userId))
                {
                    bool   doReplacement = false;
                    string urlName       = String.Empty;

                    //Get the User
                    var user = UserController.GetUserById(portalSettings.PortalId, userId);

                    if (user != null && !String.IsNullOrEmpty(user.VanityUrl))
                    {
                        doReplacement = true;
                        urlName       = (!String.IsNullOrEmpty(settings.VanityUrlPrefix)) ? String.Format("{0}/{1}", settings.VanityUrlPrefix, user.VanityUrl) : user.VanityUrl;
                        urlWasChanged = true;
                    }

                    if (doReplacement)
                    {
                        //check to see whether this is a match on the parentid or not
                        if (portalSettings.UserTabId == tab.ParentId && portalSettings.UserTabId > -1)
                        {
                            //replacing for the parent tab id
                            string childTabPath = TabIndexController.GetTabPath(tab, options, parentTraceId);
                            if (string.IsNullOrEmpty(childTabPath) == false)
                            {
                                //remove the parent tab path from the child tab path
                                TabInfo profilePage     = TabController.Instance.GetTab(tab.ParentId, tab.PortalID, false);
                                string  profilePagePath = TabIndexController.GetTabPath(profilePage, options, parentTraceId);
                                if (childTabPath.Contains(profilePagePath))
                                {
                                    //only replace when the child tab path contains the parent path - if it's a custom url that
                                    //doesn't incorporate the parent path, then leave it alone
                                    childTabPath = childTabPath.Replace(profilePagePath, "");
                                    childTabPath = childTabPath.Replace("//", "/");
                                    urlName     += FriendlyUrlController.EnsureLeadingChar("/", childTabPath);
                                }
                            }
                        }
                        changedPath = "/" + urlName;
                        //append any extra remaining path value to the end
                        if (!string.IsNullOrEmpty(remainingPath))
                        {
                            if (remainingPath.StartsWith("/") == false)
                            {
                                changedPath += "/" + remainingPath;
                            }
                            else
                            {
                                changedPath += remainingPath;
                            }
                        }
                        urlWasChanged        = true;
                        changeToSiteRoot     = true; //we will be doing domain.com/urlname
                        allowOtherParameters = false;
                        //can't have any others (wouldn't have matched in the regex if there were)
                    }
                    else
                    {
                        meessages.Add("User Profile : doReplacement = false");
                    }
                }
            }
            return(urlWasChanged);
        }
        internal static bool TransformFriendlyUrlPath(string newUrl,
                                                      string tabKeyVal,
                                                      string[] urlParms,
                                                      bool isSiteRootMatch,
                                                      ref UrlAction result,
                                                      FriendlyUrlSettings settings,
                                                      out string rewrittenUrl,
                                                      out bool newAction,
                                                      ref List <string> messages,
                                                      Guid parentTraceId)
        {
            bool rewriteDone = false;

            rewrittenUrl = newUrl;
            newAction    = false;
            ExtensionUrlProvider activeProvider = null;

            try
            {
                int tabId = result.TabId;
                if (isSiteRootMatch)
                {
                    tabId = RewriteController.SiteRootRewrite;
                }
                List <ExtensionUrlProvider> providersToCall = GetProvidersToCall(tabId,
                                                                                 result.PortalId,
                                                                                 settings,
                                                                                 parentTraceId);
                if (providersToCall != null && providersToCall.Count > 0)
                {
                    //now check for providers by calling the providers
                    int upperBound = urlParms.GetUpperBound(0);
                    //clean extension off parameters array
                    var parms = new string[upperBound + 1];
                    Array.ConstrainedCopy(urlParms, 0, parms, 0, upperBound + 1);
                    if (upperBound >= 0)
                    {
                        bool replaced;
                        parms[upperBound] = RewriteController.CleanExtension(parms[upperBound], settings, out replaced);
                    }
                    //get options from current settings
                    FriendlyUrlOptions options = UrlRewriterUtils.GetOptionsFromSettings(settings);
                    foreach (ExtensionUrlProvider provider in providersToCall)
                    {
                        //set active provider for exception handling
                        activeProvider = provider;
                        //call down to specific providers and see if we get a rewrite
                        string location;
                        int    status;
                        string queryString = provider.TransformFriendlyUrlToQueryString(parms,
                                                                                        result.TabId,
                                                                                        result.PortalId,
                                                                                        options,
                                                                                        result.CultureCode,
                                                                                        result.PortalAlias,
                                                                                        ref messages,
                                                                                        out status,
                                                                                        out location);
                        if (status == 0 || status == 200) //either not set, or set to '200 OK'.
                        {
                            if (!string.IsNullOrEmpty(queryString) && queryString != newUrl)
                            {
                                rewriteDone = true;
                                //check for duplicate tabIds.
                                string qsRemainder = null;
                                if (Regex.IsMatch(queryString, @"tabid=\d+", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))
                                {
                                    //930 : look for other querystring information in the rewritten Url, or invalid rewritten urls can be created
                                    //pattern to determine which tab matches
                                    //look for any other querystirng information in the already rewritten Url (ie language parameters)
                                    Match rewrittenUrlMatch = RewrittenUrlRegex.Match(rewrittenUrl);
                                    if (rewrittenUrlMatch.Groups["qs"].Success)
                                    {
                                        //keep any other querystring remainders
                                        qsRemainder = rewrittenUrlMatch.Groups["qs"].Captures.Cast <Capture>().Aggregate("", (current, qsCapture) => current + qsCapture.Value); //initialise
                                    }
                                    //supplied value overwrites existing value, so remove from the rewritten url
                                    rewrittenUrl = RewrittenUrlRegex.Replace(rewrittenUrl, "");
                                }
                                if (rewrittenUrl.Contains("?") == false)
                                {
                                    //use a leading ?, not a leading &
                                    queryString = FriendlyUrlController.EnsureNotLeadingChar("&", queryString);
                                    queryString = FriendlyUrlController.EnsureLeadingChar("?", queryString);
                                }
                                else
                                {
                                    //use a leading &, not a leading ?
                                    queryString = FriendlyUrlController.EnsureNotLeadingChar("?", queryString);
                                    queryString = FriendlyUrlController.EnsureLeadingChar("&", queryString);
                                }

                                //add querystring onto rewritten Url
                                rewrittenUrl += queryString;
                                if (qsRemainder != null)
                                {
                                    rewrittenUrl += qsRemainder;
                                }
                                break;
                            }
                        }
                        else
                        {
                            switch (status)
                            {
                            case 301:
                                result.Action   = ActionType.Redirect301;
                                result.Reason   = RedirectReason.Module_Provider_Rewrite_Redirect;
                                result.FinalUrl = location;
                                break;

                            case 302:
                                result.Action   = ActionType.Redirect302;
                                result.Reason   = RedirectReason.Module_Provider_Rewrite_Redirect;
                                result.FinalUrl = location;
                                break;

                            case 404:
                                result.Action = ActionType.Output404;
                                break;

                            case 500:
                                result.Action = ActionType.Output500;
                                break;
                            }
                            newAction = true; //not doing a 200 status
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //log module provider exception
                LogModuleProviderExceptionInRequest(ex, "500 Internal Server Error", activeProvider, result, messages);
                //reset values to initial
                rewriteDone  = false;
                rewrittenUrl = newUrl;
                newAction    = false;
                string providerName = "Unknown";
                if (activeProvider != null)
                {
                    providerName = activeProvider.ProviderConfig.ProviderName;
                }
                if (result != null)
                {
                    result.DebugMessages.Add("Exception in provider [" + providerName + "] :" + ex.Message);
                }
            }
            return(rewriteDone);
        }
 protected string EnsureLeadingChar(string leading, string path)
 {
     return(FriendlyUrlController.EnsureLeadingChar(leading, path));
 }