Exemplo n.º 1
0
        public DnnUnitTest(int portalId)
        {
            var simulator = new HttpSimulator.HttpSimulator();

            simulator.SimulateRequest();

            InstallComponents();

            LoadDnnProviders("data;logging;caching;authentication;members;roles;profiles;permissions;folder");

            //fix Globals.ApplicationMapPath
            var appPath = ConfigurationManager.AppSettings["DefaultPhysicalAppPath"];

            if (!string.IsNullOrEmpty(appPath))
            {
                var mappath = typeof(Globals).GetField("_applicationMapPath", BindingFlags.Static | BindingFlags.NonPublic);
                mappath.SetValue(null, appPath);
            }

            //fix membership
            var providerProp = typeof(Membership).GetField("s_Provider", BindingFlags.Static | BindingFlags.NonPublic);

            providerProp.SetValue(null, Membership.Providers["AspNetSqlMembershipProvider"]);

            var objPortalAliasInfo = new DotNetNuke.Entities.Portals.PortalAliasInfo {
                PortalID = portalId
            };
            var ps = new DotNetNuke.Entities.Portals.PortalSettings(59, objPortalAliasInfo);

            System.Web.HttpContext.Current.Items.Add("PortalSettings", ps);
            SqlProvider = new SqlDataProvider();
            PortalId    = portalId;
        }
Exemplo n.º 2
0
        public DnnUnitTest(int portalId)
        {
            var simulator = new HttpSimulator.HttpSimulator();
            simulator.SimulateRequest();

            InstallComponents();

            LoadDnnProviders("data;logging;caching;authentication;members;roles;profiles;permissions;folder");

            //fix Globals.ApplicationMapPath
            var appPath = ConfigurationManager.AppSettings["DefaultPhysicalAppPath"];
            if(!string.IsNullOrEmpty(appPath))
            {
                var mappath = typeof (Globals).GetField("_applicationMapPath", BindingFlags.Static | BindingFlags.NonPublic);
                mappath.SetValue(null, appPath);
            }

            //fix membership
            var providerProp = typeof(Membership).GetField("s_Provider", BindingFlags.Static | BindingFlags.NonPublic);
            providerProp.SetValue(null, Membership.Providers["AspNetSqlMembershipProvider"]);

            var objPortalAliasInfo = new DotNetNuke.Entities.Portals.PortalAliasInfo { PortalID = portalId };
            var ps = new DotNetNuke.Entities.Portals.PortalSettings(59, objPortalAliasInfo);
            System.Web.HttpContext.Current.Items.Add("PortalSettings", ps);
            SqlProvider = new SqlDataProvider();
            PortalId = portalId;
        }
Exemplo n.º 3
0
        public AutomationBase()
        {
            if (Driver == null)
            {
                var simulator = new HttpSimulator.HttpSimulator();
                simulator.SimulateRequest();

                InstallComponents();

                LoadDnnProviders("data;logging;caching;authentication;members;roles;profiles;permissions;folder");

                //fix Globals.ApplicationMapPath
                var appPath = ConfigurationManager.AppSettings["DefaultPhysicalAppPath"];
                if (!string.IsNullOrEmpty(appPath))
                {
                    var mappath = typeof(Globals).GetField("_applicationMapPath", BindingFlags.Static | BindingFlags.NonPublic);
                    mappath.SetValue(null, appPath);
                }

                //fix membership
                var providerProp = typeof(Membership).GetField("s_Provider", BindingFlags.Static | BindingFlags.NonPublic);
                providerProp.SetValue(null, Membership.Providers["AspNetSqlMembershipProvider"]);

                var objPortalAliasInfo = new DotNetNuke.Entities.Portals.PortalAliasInfo {
                    PortalID = _portalId
                };
                var ps = new DotNetNuke.Entities.Portals.PortalSettings(59, objPortalAliasInfo);
                System.Web.HttpContext.Current.Items.Add("PortalSettings", ps);
                SqlProvider = new SqlDataProvider();
                PortalId    = _portalId;

                switch (_browser)
                {
                case Common.BrowserType.firefox:
                    _ffp = new FirefoxProfile {
                        AcceptUntrustedCertificates = true
                    };
                    Driver = new FirefoxDriver(_ffp);
                    Driver.Navigate().GoToUrl(SiteUrl);
                    break;

                case Common.BrowserType.ie:
                    Driver = new InternetExplorerDriver();
                    Driver.Navigate().GoToUrl(SiteUrl);
                    break;

                case Common.BrowserType.chrome:
                    Driver = new ChromeDriver();
                    Driver.Navigate().GoToUrl(SiteUrl);
                    break;
                }
            }
        }
Exemplo n.º 4
0
        public static string GetChildPortalAlias(this DotNetNuke.Entities.Portals.PortalAliasInfo portalAlias)
        {
            var currentAlias = portalAlias.HTTPAlias;
            var index        = currentAlias.IndexOf('/');

            if (index > 0)
            {
                return("/" + currentAlias.Substring(index + 1));
            }
            else
            {
                return("");
            }
        }
Exemplo n.º 5
0
        public static string ResolveUrl(this DotNetNuke.Entities.Portals.PortalAliasInfo portalAlias, string url)
        {
            url = url.TrimStart('~');
            url = url.TrimStart('/');
            var childPortalAlias = portalAlias.GetChildPortalAlias();

            if (childPortalAlias.StartsWith(DotNetNuke.Common.Globals.ApplicationPath))
            {
                return(String.Format("{0}/{1}", childPortalAlias, url));
            }
            else
            {
                return(String.Format("{0}{1}/{2}", DotNetNuke.Common.Globals.ApplicationPath, childPortalAlias, url));
            }
        }
Exemplo n.º 6
0
        public virtual void ProcessRequest(System.Web.HttpContext context)
        {
            try
            {
                if (HttpContext.Current.Items["PortalSettings"] != null)
                {
                    _ps  = (DotNetNuke.Entities.Portals.PortalSettings)(HttpContext.Current.Items["PortalSettings"]);
                    _pid = _ps.PortalId;
                }
                else
                {
                    string DomainName = null;
                    DotNetNuke.Entities.Portals.PortalAliasInfo objPortalAliasInfo = null;
                    string sUrl = HttpContext.Current.Request.RawUrl.Replace("http://", string.Empty).Replace("https://", string.Empty);
                    objPortalAliasInfo = DotNetNuke.Entities.Portals.PortalAliasController.Instance.GetPortalAlias(HttpContext.Current.Request.Url.Host);
                    _pid = objPortalAliasInfo.PortalID;
                    _ps  = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings();
                }

                //Dim sc As New Social.SocialSettings
                //_mainSettings = sc.LoadSettings[_ps.PortalId]
                _mainSettings = DataCache.MainSettings(ModuleId);
                //  If context.Request.IsAuthenticated Then
                _isValid = true;
                if (AdminRequired & !context.Request.IsAuthenticated)
                {
                    _isValid = false;
                    return;
                }
                if (AdminRequired && context.Request.IsAuthenticated)
                {
                    //_isValid = DotNetNuke.Security.PortalSecurity.IsInRole(_ps.AdministratorRoleName)
                    DotNetNuke.Entities.Modules.ModuleController objMC = new DotNetNuke.Entities.Modules.ModuleController();
                    DotNetNuke.Entities.Modules.ModuleInfo       objM  = objMC.GetModule(ModuleId, TabId);
                    string roleIds = Permissions.GetRoleIds(objM.ModulePermissions.ToString("EDIT").Split(';'), PortalId);
                    _isValid = Modules.ActiveForums.Permissions.HasAccess(roleIds, ForumUser.UserRoles);
                }
                else if (AdminRequired & !context.Request.IsAuthenticated)
                {
                    _isValid = false;
                    return;
                }
                string p = HttpContext.Current.Request.Params["p"];
                if (!(string.IsNullOrEmpty(p)))
                {
                    _params = Utilities.JSON.ConvertFromJSONAssoicativeArrayToHashTable(p);
                }

                if (context.Request.Files.Count == 0)
                {
                    string jsonPost     = string.Empty;
                    string prop         = string.Empty;
                    bool   propComplete = true;
                    string val          = string.Empty;
                    string tmp          = string.Empty;
                    bool   bObj         = false;
                    //Arrays
                    List <string> slist = null;
                    //Dim pairs As NameValueCollection = Nothing
                    Hashtable pairs    = null;
                    Hashtable subPairs = null;

                    Hashtable ht         = new Hashtable();
                    int       idx        = 0;
                    string    parentProp = string.Empty;
                    string    skip       = "{}[]:," + ((char)(34)).ToString();
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream, System.Text.Encoding.UTF8))
                    {
                        while (!(sr.EndOfStream))
                        {
                            char c = (char)(sr.Read());
                            if (idx > 0 && c == '[')
                            {
                                c    = (char)(sr.Read());
                                bObj = true;
                            }
                            if (idx > 0 && c == '{')
                            {
                                if (pairs == null)
                                {
                                    parentProp = prop;
                                    prop       = string.Empty;
                                    tmp        = string.Empty;
                                    //pairs = New NameValueCollection
                                    pairs = new Hashtable();
                                }
                                else if (subPairs == null)
                                {
                                    string subString = c.ToString();
                                    while (c != '}')
                                    {
                                        c          = (char)(sr.Read());
                                        subString += c;
                                        if (c == '}')
                                        {
                                            break;
                                        }
                                    }
                                    subPairs = Utilities.JSON.ConvertFromJSONAssoicativeArrayToHashTable(subString);
                                    pairs.Add(prop, subPairs);
                                    prop     = string.Empty;
                                    tmp      = string.Empty;
                                    subPairs = null;
                                    c        = (char)(sr.Read());
                                }
                            }

                            if (idx > 0 && bObj == true && !(c == '{'))
                            {
                                string subItem = string.Empty;
                                while (c != ']')
                                {
                                    if (slist == null)
                                    {
                                        slist = new List <string>();
                                    }
                                    if (skip.IndexOf(c) == -1)
                                    {
                                        subItem += c;
                                    }

                                    c = (char)(sr.Read());
                                    if (c == ',' || c == ']')
                                    {
                                        slist.Add(subItem);
                                        subItem = string.Empty;
                                    }
                                    if (c == ']')
                                    {
                                        c    = (char)(sr.Read());
                                        bObj = false;
                                        break;
                                    }
                                }
                            }
                            if (c == ':')
                            {
                                prop = tmp;
                                tmp  = string.Empty;
                            }
                            if (skip.IndexOf(c) == -1)
                            {
                                tmp += c;
                            }
                            if (c == ',' || c == '}')
                            {
                                if (!(string.IsNullOrEmpty(tmp)))
                                {
                                    tmp = HttpUtility.UrlDecode(tmp);
                                }
                                if (slist != null)
                                {
                                    ht.Add(prop, slist);
                                    slist = null;
                                }
                                else if (pairs != null && c == ',' && !(string.IsNullOrEmpty(prop)))
                                {
                                    pairs.Add(prop, tmp);
                                }
                                else if (pairs != null && c == '}')
                                {
                                    if (!(string.IsNullOrEmpty(tmp)))
                                    {
                                        pairs.Add(prop, tmp);
                                    }
                                    ht.Add(parentProp, pairs);
                                    parentProp = string.Empty;
                                    pairs      = null;
                                }
                                else if (!(string.IsNullOrEmpty(prop)))
                                {
                                    ht.Add(prop, tmp);
                                }

                                prop = string.Empty;
                                tmp  = string.Empty;
                            }

                            idx += 1;
                        }
                        if (pairs != null & !(string.IsNullOrEmpty(parentProp)))
                        {
                            ht.Add(parentProp, pairs);
                        }
                        else if (!(string.IsNullOrEmpty(prop)) && !(string.IsNullOrEmpty(tmp)))
                        {
                            ht.Add(prop, HttpUtility.UrlDecode(tmp));
                        }
                        else if (!(string.IsNullOrEmpty(prop)) && slist != null)
                        {
                            ht.Add(prop, slist);
                        }

                        //jsonPost = sr.ReadToEnd()
                        sr.Close();
                    }
                    _params = ht;
                    //End If
                }
                else
                {
                    Hashtable ht = new Hashtable();
                    foreach (string s in context.Request.Params.AllKeys)
                    {
                        if (!(ht.ContainsKey(s)))
                        {
                            ht.Add(s, context.Request.Params[s]);
                        }
                    }
                    _params = ht;
                }

                if (HttpContext.Current.Request.IsAuthenticated)
                {
                    UserId = UserController.GetUserIdByUserName(PortalId, HttpContext.Current.User.Identity.Name);
                }
                else
                {
                    UserId = -1;
                }
            }
            catch (Exception ex)
            {
                _isValid = false;
                Exceptions.LogException(ex);
            }
        }
        /// <summary>
        /// This method is used by the Url Master Url Rewriting process.  The purpose of this method is to take the supplied array of Url parameters, and transform them into a module-specific querystring for the underlying re-written Url.
        /// </summary>
        /// <param name="urlParms">The array of parameters found after the DNN page path has been identified.  No key/valeu pairs are identified, the parameters are converted from the /key/value/key2/value2 format into [key,value,key2,value2] format.</param>
        /// <param name="tabId">TabId of identified DNN page.</param>
        /// <param name="portalId">PortalId of identified DNN portal.</param>
        /// <param name="options">The current Friendly Url options being used by the module.</param>
        /// <param name="cultureCode">Identified language/culture code, if supplied.</param>
        /// <param name="portalAlias">Identified portalAlias object for the request.</param>
        /// <param name="messages">List of debug messages.  Add to this list to help debug your module.  Can be viewed in the reponse headers of the request, or in the 'Test Url Rewriting' section of the Url Master module.</param>
        /// <param name="status">Out parameter, returns the Http status of the request.  May be 200,301,302, or 404.  For normal rewriting, return a 200 value.</param>
        /// <param name="location">If a 301 or 302 is returned in the status parameter, then this must contain a valid redirect location.  This should be a fully-qualified Url.</param>
        /// <returns>The querystring to be used for rewriting the Url. NOTE: doesn't need to include the tabid if the tabid parameter is &gt; -1</returns>
        public override string TransformFriendlyUrlToQueryString(string[] urlParms, int tabId, int portalId, iFinity.DNN.Modules.UrlMaster.FriendlyUrlOptions options, string cultureCode, DotNetNuke.Entities.Portals.PortalAliasInfo portalAlias, ref List <string> messages, out int status, out string location)
        {
            //store local options variable
            _options = options;
            //initialise results and output variables
            string result = ""; status = 200; //OK

            location = null;                  //no redirect location
            if (messages == null)
            {
                messages = new List <string>();
            }

            return(result);
        }
        /// <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
                        DotNetNuke.Entities.Portals.PortalAliasInfo alias = DotNetNuke.Entities.Portals.PortalAliasController.Instance.GetPortalAlias(httpAlias);
                        DotNetNuke.Entities.Portals.PortalSettings  ps    = new DotNetNuke.Entities.Portals.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);
        }
        /// <summary>
        /// This method is used by the Url Master Url Rewriting process.  The purpose of this method is to take the supplied array of Url parameters, and transform them into a module-specific querystring for the underlying re-written Url.
        /// </summary>
        /// <param name="urlParms">The array of parameters found after the DNN page path has been identified.  No key/valeu pairs are identified, the parameters are converted from the /key/value/key2/value2 format into [key,value,key2,value2] format.</param>
        /// <param name="tabId">TabId of identified DNN page. </param>
        /// <param name="portalId">PortalId of identified DNN portal.</param>
        /// <param name="options">The current Friendly Url options being used by the module.</param>
        /// <param name="cultureCode">Identified language/culture code, if supplied.</param>
        /// <param name="portalAlias">Identified portalAlias object for the request.</param>
        /// <param name="messages">List of debug messages.  Add to this list to help debug your module.  Can be viewed in the reponse headers of the request, or in the 'Test Url Rewriting' section of the Url Master module.</param>
        /// <param name="status">Out parameter, returns the Http status of the request.  May be 200,301,302, or 404.  For normal rewriting, return a 200 value.</param>
        /// <param name="location">If a 301 or 302 is returned in the status parameter, then this must contain a valid redirect location.  This should be a fully-qualified Url.</param>
        /// <returns>The querystring to be used for rewriting the Url. NOTE: doesn't need to include the tabid if the tabid parameter is > -1</returns>
        public override string TransformFriendlyUrlToQueryString(string[] urlParms, int tabId, int portalId, FriendlyUrlOptions options, string cultureCode, DotNetNuke.Entities.Portals.PortalAliasInfo portalAlias, ref List <string> messages, out int status, out string location)
        {
            string path = string.Join("/", urlParms);

            //initialise results and output variables
            location = null; //no redirect location
            if (messages == null)
            {
                messages = new List <string>();
            }
            string result = ""; status = 200; //OK

            //prevent incorrect matches of Urls
            if (!Regex.IsMatch(path, @"(articleType/(?<type>[^/]+))|(ctl/[^/]+/(mid|moduleid)/\d)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))
            {
                //store local options variable
                _options = options;
                //get the tab options
                TabUrlOptions urlOptions       = GetTabUrlOptions(tabId);
                Hashtable     queryStringIndex = null;
                int           skipUpToIndex    = -1;
                bool          found            = false;
                bool          siteRootMatch    = false;
                //look for match on pattern for date and title - the pattern used by this provider
                //string path = string.Join("/", urlParms);
                //messages.Add("Checking for Items in Friendly Url path: " + path);
                if (urlParms.Length > 0)
                {
                    //tabid == -1 when no dnn page path is in the Url.  This means the Url Master module can't determine the DNN page based on the Url.
                    //In this case, it is up to this provider to identify the correct tabId that matches the Url.  Failure to do so will result in the incorrect tab being loaded when the page is rendered.
                    if (tabId == -1)
                    {
                        siteRootMatch = true;
                        if (_noDnnPagePathTabId > -1)
                        {
                            //tabid -1 means a 'site root' match - meaning that the dnn page path wasn't included in the Url
                            tabId = _noDnnPagePathTabId;//if tabid = -1, it means a site root match (no dnn page path) so we substitute in the tabid where this is being used
                        }
                    }
                    queryStringIndex = UrlController.GetQueryStringIndex(tabId, portalId, this, options, urlOptions, false);
                    string pathBasedKey = string.Join("/", urlParms).ToLower();
                    string qs           = null;
                    if (queryStringIndex.ContainsKey(pathBasedKey))
                    {
                        //that was easy-  direct match
                        qs            = (string)queryStringIndex[pathBasedKey];
                        skipUpToIndex = urlParms.GetUpperBound(0);
                    }
                    else
                    {
                        //go through the parameter list backwards until we find a match
                        for (int i = urlParms.GetUpperBound(0); i >= 0; i--)
                        {
                            //copy all the array minus the i index item
                            int      tempLength = i + 1;
                            string[] tempParms  = new string[tempLength];
                            Array.Copy(urlParms, 0, tempParms, 0, i + 1);
                            //make a new key from the shorter array
                            pathBasedKey = string.Join("/", tempParms).ToLower();
                            //check if that matches
                            if (queryStringIndex.ContainsKey(pathBasedKey))
                            {
                                qs = (string)queryStringIndex[pathBasedKey];
                                if (qs != null)
                                {
                                    //the trimmed pieces need to be included
                                    skipUpToIndex = i;
                                    break;
                                }
                            }
                        }
                    }
                    if (qs != null)
                    {
                        //found a querystring match
                        found = true;
                        messages.Add("Item Matched in Friendly Url Provider.  Url : " + pathBasedKey + " Path : " + path);
                        result += qs;
                    }
                    else
                    {
                        //no match, but look for a date archive pattern
                        //903 : issue with matching other Urls that aren't archive Urls
                        Regex archivePatternRegex = new Regex(@"(?<!year)(?<yr>(^|/)(?<yyyy>[\d]{4}))(?<mth>/(?<mm>[\d]{1,2}))?", RegexOptions.IgnoreCase);
                        Match archivePatternMatch = archivePatternRegex.Match(path);
                        if (archivePatternMatch.Success)
                        {
                            bool   month = false, year = false;
                            string mm = null, yyyy = null;
                            //matched on date pattern, extract month/year
                            Group mthGrp = archivePatternMatch.Groups["mth"];
                            if (mthGrp != null && mthGrp.Success)
                            {
                                mm    = archivePatternMatch.Groups["mm"].Value;
                                month = true;
                            }
                            Group yrGrp = archivePatternMatch.Groups["yyyy"];
                            if (yrGrp != null && yrGrp.Success)
                            {
                                //902 : don't allow invalid dates to be passed down
                                int yearVal = 0;
                                yyyy = yrGrp.Value;
                                //check that year is a valid int, and that year is later than sql min date time
                                if (int.TryParse(yyyy, out yearVal) && yearVal > 1753)
                                {
                                    year = true;
                                }
                            }
                            if (year)
                            {
                                qs = "";
                                if (this.NoDnnPagePathTabId == tabId)
                                {
                                    qs += "?tabid=" + tabId.ToString();
                                }
                                //add on the year
                                qs           += "&articleType=ArchiveView&year=" + yyyy;
                                skipUpToIndex = 0;//1st position
                            }
                            if (year && month)
                            {
                                int mmVal = 0;
                                if (int.TryParse(mm, out mmVal) && mmVal > 0 && mmVal < 13)
                                {
                                    qs           += "&month=" + mm;
                                    skipUpToIndex = 1;//2nd position
                                }
                            }
                            if (year || month)
                            {
                                result += qs;
                            }
                        }
                    }
                }

                if (skipUpToIndex >= 0)
                {
                    //put on any remainder of the path that wasn't to do with the friendly Url
                    //but only if there was *something* in the friendly url that we interpreted
                    string remainder = base.CreateQueryStringFromParameters(urlParms, skipUpToIndex);
                    //put it all together for the final rewrite string
                    result += remainder;
                }
            }
            return(result);
        }
Exemplo n.º 10
0
        public void OnBeginRequest(object s, EventArgs e)
        {
            _forumId      = -1;
            _tabId        = -1;
            _moduleId     = -1;
            _topicId      = -1;
            _page         = 1;
            _contentId    = -1;
            _archived     = 0;
            _forumgroupId = -1;
            _mainSettings = null;
            _categoryId   = -1;
            _tagId        = -1;

            HttpApplication   app           = (HttpApplication)s;
            HttpServerUtility Server        = app.Server;
            HttpRequest       Request       = app.Request;
            HttpResponse      Response      = app.Response;
            string            requestedPath = app.Request.Url.AbsoluteUri;
            HttpContext       Context       = ((HttpApplication)s).Context;
            int PortalId = -1;

            DotNetNuke.Entities.Portals.PortalAliasInfo objPortalAliasInfo = null;
            string sUrl = HttpContext.Current.Request.RawUrl.Replace("http://", string.Empty).Replace("https://", string.Empty);

            objPortalAliasInfo = DotNetNuke.Entities.Portals.PortalSettings.GetPortalAliasInfo(HttpContext.Current.Request.Url.Host);
            if (Request.RawUrl.ToLowerInvariant().Contains("404.aspx"))
            {
                string sEx = ".jpg,.gif,.png,.swf,.js,.css,.html,.htm,desktopmodules,portals,.ashx,.ico,.txt,.doc,.docx,.pdf,.xml,.xls,.xlsx,.ppt,.pptx,.csv,.zip,.asmx,.aspx";
                foreach (string sn in sEx.Split(','))
                {
                    if (sUrl.Contains(sn))
                    {
                        // IO.File.AppendAllText(sPath, Request.RawUrl & "165<br />")
                        return;
                    }
                }
            }
            if (Request.Url.LocalPath.ToLower().Contains("scriptresource.axd") || Request.Url.LocalPath.ToLower().Contains("webresource.axd") || Request.Url.LocalPath.ToLower().Contains("viewer.aspx") || Request.Url.LocalPath.ToLower().Contains("cb.aspx") || Request.Url.LocalPath.ToLower().Contains("filesupload.aspx") || Request.Url.LocalPath.ToLower().Contains(".gif") || Request.Url.LocalPath.ToLower().Contains(".jpg") || Request.Url.LocalPath.ToLower().Contains(".css") || Request.Url.LocalPath.ToLower().Contains(".png") || Request.Url.LocalPath.ToLower().Contains(".swf") || Request.Url.LocalPath.ToLower().Contains(".htm") || Request.Url.LocalPath.ToLower().Contains(".html") || Request.Url.LocalPath.ToLower().Contains(".ashx") || Request.Url.LocalPath.ToLower().Contains(".cur") || Request.Url.LocalPath.ToLower().Contains(".ico") || Request.Url.LocalPath.ToLower().Contains(".txt") || Request.Url.LocalPath.ToLower().Contains(".pdf") || Request.Url.LocalPath.ToLower().Contains(".xml") || Request.Url.LocalPath.ToLower().Contains("/portals/") || Request.Url.LocalPath.ToLower().Contains("/desktopmodules/") || Request.Url.LocalPath.ToLower().Contains("evexport.aspx") || Request.Url.LocalPath.ToLower().Contains("signupjs.aspx") || Request.Url.LocalPath.ToLower().Contains("evsexport.aspx") || Request.Url.LocalPath.ToLower().Contains("fbcomm.aspx") || Request.Url.LocalPath.ToLower().Contains(".aspx") || Request.Url.LocalPath.ToLower().Contains(".js"))
            {
                return;
            }
            if (Request.Url.LocalPath.ToLower().Contains("install.aspx") || Request.Url.LocalPath.ToLower().Contains("installwizard.aspx") || Request.Url.LocalPath.ToLower().Contains("captcha.aspx") || Request.RawUrl.Contains("viewer.aspx") || Request.RawUrl.Contains("blank.html") || Request.RawUrl.Contains("default.htm") || Request.RawUrl.Contains("autosuggest.aspx"))
            {
                return;
            }
            PortalId = objPortalAliasInfo.PortalID;
            string searchURL = sUrl;

            searchURL = searchURL.Replace(objPortalAliasInfo.HTTPAlias, string.Empty);
            if (searchURL.Length < 2)
            {
                return;
            }
            string query = string.Empty;

            if (searchURL.Contains("?"))
            {
                query     = searchURL.Substring(searchURL.IndexOf("?"));
                searchURL = searchURL.Substring(0, searchURL.IndexOf("?") - 1);
            }
            string newSearchURL = string.Empty;

            foreach (string up in searchURL.Split('/'))
            {
                if (!(string.IsNullOrEmpty(up)))
                {
                    if (!(SimulateIsNumeric.IsNumeric(up)))
                    {
                        newSearchURL += up + "/";
                    }
                }
            }
            bool canContinue = false;

            Data.Common db      = new Data.Common();
            string      tagName = string.Empty;
            string      catName = string.Empty;

            if (newSearchURL.Contains("/category/") || newSearchURL.Contains("/tag/"))
            {
                if (newSearchURL.Contains("/category/"))
                {
                    string cat       = "/category/";
                    int    iEnd      = newSearchURL.IndexOf("/", newSearchURL.IndexOf(cat) + cat.Length + 1);
                    string catString = newSearchURL.Substring(newSearchURL.IndexOf(cat), iEnd - newSearchURL.IndexOf(cat));
                    catName      = catString.Replace(cat, string.Empty);
                    catName      = catName.Replace("/", string.Empty);
                    newSearchURL = newSearchURL.Replace(catString, string.Empty);
                }
                if (newSearchURL.Contains("/tag/"))
                {
                    string tag       = "/tag/";
                    int    iEnd      = newSearchURL.IndexOf("/", newSearchURL.IndexOf(tag) + tag.Length + 1);
                    string tagString = newSearchURL.Substring(newSearchURL.IndexOf(tag), iEnd - newSearchURL.IndexOf(tag));
                    tagName      = tagString.Replace(tag, string.Empty);
                    tagName      = tagName.Replace("/", string.Empty);
                    newSearchURL = newSearchURL.Replace(tagString, string.Empty);
                }
            }
            if ((sUrl.Contains("afv") && sUrl.Contains("post")) | (sUrl.Contains("afv") && sUrl.Contains("confirmaction")) | (sUrl.Contains("afv") && sUrl.Contains("sendto")) | (sUrl.Contains("afv") && sUrl.Contains("modreport")) | (sUrl.Contains("afv") && sUrl.Contains("search")) | sUrl.Contains("dnnprintmode") || sUrl.Contains("asg") || (sUrl.Contains("afv") && sUrl.Contains("modtopics")))
            {
                return;
            }
            try
            {
                using (IDataReader dr = db.URLSearch(PortalId, newSearchURL))
                {
                    while (dr.Read())
                    {
                        _tabId        = int.Parse(dr["TabID"].ToString());
                        _moduleId     = int.Parse(dr["ModuleId"].ToString());
                        _forumgroupId = int.Parse(dr["ForumGroupId"].ToString());
                        _forumId      = int.Parse(dr["ForumId"].ToString());
                        _topicId      = int.Parse(dr["TopicId"].ToString());
                        _archived     = int.Parse(dr["Archived"].ToString());
                        _otherId      = int.Parse(dr["OtherId"].ToString());
                        _urlType      = int.Parse(dr["UrlType"].ToString());
                        canContinue   = true;
                    }
                    dr.Close();
                }
            }
            catch (Exception ex)
            {
            }
            if (!(string.IsNullOrEmpty(catName)))
            {
                _categoryId = db.Tag_GetIdByName(PortalId, _moduleId, catName, true);
                _otherId    = _categoryId;
                _urlType    = 2;
            }
            if (!(string.IsNullOrEmpty(tagName)))
            {
                _tagId   = db.Tag_GetIdByName(PortalId, _moduleId, tagName, false);
                _otherId = _tagId;
                _urlType = 3;
            }

            if (_archived == 1)
            {
                sUrl = db.GetUrl(_moduleId, _forumgroupId, _forumId, _topicId, _userId, -1);
                if (!(string.IsNullOrEmpty(sUrl)))
                {
                    string sHost = objPortalAliasInfo.HTTPAlias;
                    if (sUrl.StartsWith("/"))
                    {
                        sUrl = sUrl.Substring(1);
                    }
                    if (!(sHost.EndsWith("/")))
                    {
                        sHost += "/";
                    }
                    sUrl = sHost + sUrl;
                    if (!(sUrl.EndsWith("/")))
                    {
                        sUrl += "/";
                    }
                    if (!(sUrl.StartsWith("http")))
                    {
                        if (Request.IsSecureConnection)
                        {
                            sUrl = "https://" + sUrl;
                        }
                        else
                        {
                            sUrl = "http://" + sUrl;
                        }
                    }
                    Response.Clear();
                    Response.Status = "301 Moved Permanently";
                    Response.AddHeader("Location", sUrl);
                    Response.End();
                }
            }
            if (_moduleId > 0)
            {
                Entities.Modules.ModuleController objModules = new Entities.Modules.ModuleController();
                SettingsInfo objSettings = new SettingsInfo();
                objSettings.MainSettings = objModules.GetModuleSettings(_moduleId);
                _mainSettings            = objSettings;      // DataCache.MainSettings(_moduleId)
            }
            if (_mainSettings == null)
            {
                return;
            }
            if (!_mainSettings.URLRewriteEnabled)
            {
                return;
            }
            if (!canContinue && (Request.RawUrl.Contains(ParamKeys.TopicId) || Request.RawUrl.Contains(ParamKeys.ForumId) || Request.RawUrl.Contains(ParamKeys.GroupId)))
            {
                sUrl = HandleOldUrls(Request.RawUrl, objPortalAliasInfo.HTTPAlias);
                if (!(string.IsNullOrEmpty(sUrl)))
                {
                    if (!(sUrl.StartsWith("http")))
                    {
                        if (Request.IsSecureConnection)
                        {
                            sUrl = "https://" + sUrl;
                        }
                        else
                        {
                            sUrl = "http://" + sUrl;
                        }
                    }
                    Response.Clear();
                    Response.Status = "301 Moved Permanently";
                    Response.AddHeader("Location", sUrl);
                    Response.End();
                }
            }
            if (!canContinue)
            {
                string topicUrl = string.Empty;
                if (newSearchURL.EndsWith("/"))
                {
                    newSearchURL = newSearchURL.Substring(0, newSearchURL.Length - 1);
                }
                if (newSearchURL.Contains("/"))
                {
                    topicUrl = newSearchURL.Substring(newSearchURL.LastIndexOf("/"));
                }
                topicUrl = topicUrl.Replace("/", string.Empty);
                if (!(string.IsNullOrEmpty(topicUrl)))
                {
                    Data.Topics topicsDb = new Data.Topics();
                    _topicId = topicsDb.TopicIdByUrl(PortalId, _moduleId, topicUrl.ToLowerInvariant());
                    if (_topicId > 0)
                    {
                        sUrl = db.GetUrl(_moduleId, _forumgroupId, _forumId, _topicId, _userId, -1);
                    }
                    else
                    {
                        sUrl = string.Empty;
                    }
                    if (!(string.IsNullOrEmpty(sUrl)))
                    {
                        string sHost = objPortalAliasInfo.HTTPAlias;
                        if (sHost.EndsWith("/") && sUrl.StartsWith("/"))
                        {
                            sUrl = sHost.Substring(0, sHost.Length - 1) + sUrl;
                        }
                        else if (!(sHost.EndsWith("/")) && !(sUrl.StartsWith("/")))
                        {
                            sUrl = sHost + "/" + sUrl;
                        }
                        else
                        {
                            sUrl = sHost + sUrl;
                        }
                        if (sUrl.StartsWith("/"))
                        {
                            sUrl = sUrl.Substring(1);
                        }
                        if (!(sUrl.StartsWith("http")))
                        {
                            if (Request.IsSecureConnection)
                            {
                                sUrl = "https://" + sUrl;
                            }
                            else
                            {
                                sUrl = "http://" + sUrl;
                            }
                        }
                        if (!(string.IsNullOrEmpty(sUrl)))
                        {
                            Response.Clear();
                            Response.Status = "301 Moved Permanently";
                            Response.AddHeader("Location", sUrl);
                            Response.End();
                        }
                    }
                }
            }

            if (canContinue)
            {
                if (searchURL != newSearchURL)
                {
                    string urlTail = searchURL.Replace(newSearchURL, string.Empty);
                    if (urlTail.StartsWith("/"))
                    {
                        urlTail = urlTail.Substring(1);
                    }
                    if (urlTail.EndsWith("/"))
                    {
                        urlTail = urlTail.Substring(0, urlTail.Length - 1);
                    }
                    if (urlTail.Contains("/"))
                    {
                        urlTail = urlTail.Substring(0, urlTail.IndexOf("/") - 1);
                    }
                    if (SimulateIsNumeric.IsNumeric(urlTail))
                    {
                        _page = Convert.ToInt32(urlTail);
                    }
                }

                string sPage = string.Empty;
                sPage = "&afpg=" + _page.ToString();
                string qs = string.Empty;
                if (sUrl.Contains("?"))
                {
                    qs = "&" + sUrl.Substring(sUrl.IndexOf("?") + 1);
                }
                string catQS = string.Empty;
                if (_categoryId > 0)
                {
                    catQS = "&act=" + _categoryId.ToString();
                }
                string sendTo = string.Empty;
                if (_topicId > 0)
                {
                    sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&aft=" + _topicId + sPage + qs);
                }
                else if (_forumId > 0)
                {
                    sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&aff=" + _forumId + sPage + qs + catQS);
                }
                else if (_forumgroupId > 0)
                {
                    sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&afg=" + _forumgroupId + sPage + qs + catQS);
                }
                else if (_urlType == 2 && _otherId > 0)
                {
                    sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&act=" + _otherId + sPage + qs);
                }
                else if (_urlType == 3 && _otherId > 0)
                {
                    sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&afv=grid&afgt=tags&aftg=" + _otherId + sPage + qs);
                }
                else if (_urlType == 1)
                {
                    string v = string.Empty;
                    switch (_otherId)
                    {
                    case 1:
                        v = "unanswered";
                        break;

                    case 2:
                        v = "notread";
                        break;

                    case 3:
                        v = "mytopics";
                        break;

                    case 4:
                        v = "activetopics";
                        break;
                    }
                    sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&afv=grid&afgt=" + v + sPage + qs);
                }
                else if (_tabId > 0)
                {
                    sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + sPage + qs);
                }

                RewriteUrl(app.Context, sendTo);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// This method is used by the Url Master Url Rewriting process.  The purpose of this method is to take the supplied array of Url parameters, and transform them into a module-specific querystring for the underlying re-written Url.
        /// </summary>
        /// <param name="urlParms">The array of parameters found after the DNN page path has been identified.  No key/valeu pairs are identified, the parameters are converted from the /key/value/key2/value2 format into [key,value,key2,value2] format.</param>
        /// <param name="tabId">TabId of identified DNN page. </param>
        /// <param name="portalId">PortalId of identified DNN portal.</param>
        /// <param name="options">The current Friendly Url options being used by the module.</param>
        /// <param name="cultureCode">Identified language/culture code, if supplied.</param>
        /// <param name="portalAlias">Identified portalAlias object for the request.</param>
        /// <param name="messages">List of debug messages.  Add to this list to help debug your module.  Can be viewed in the reponse headers of the request, or in the 'Test Url Rewriting' section of the Url Master module.</param>
        /// <param name="status">Out parameter, returns the Http status of the request.  May be 200,301,302, or 404.  For normal rewriting, return a 200 value.</param>
        /// <param name="location">If a 301 or 302 is returned in the status parameter, then this must contain a valid redirect location.  This should be a fully-qualified Url.</param>
        /// <returns>The querystring to be used for rewriting the Url. NOTE: doesn't need to include the tabid if the tabid parameter is > -1</returns>
        public override string TransformFriendlyUrlToQueryString(string[] urlParms, int tabId, int portalId, iFinity.DNN.Modules.UrlMaster.FriendlyUrlOptions options, string cultureCode, DotNetNuke.Entities.Portals.PortalAliasInfo portalAlias, ref List <string> messages, out int status, out string location)
        {
            //store local options variable
            _options = options;
            //initialise results and output variables
            string result = ""; status = 200; //OK

            location = null;                  //no redirect location
            if (messages == null)
            {
                messages = new List <string>();
            }

            //Hashtable queryStringIndex = null;
            //string path = string.Join("/", urlParms);
            //int skipUpToIndex = -1;
            //bool found = false;
            //bool siteRootMatch = false;
            ////look for match on pattern for date and title - the pattern used by this provider
            ////string path = string.Join("/", urlParms);
            ////messages.Add("Checking for Items in Friendly Url path: " + path);
            //if (urlParms.Length > 0)
            //{
            //    //tabid == -1 when no dnn page path is in the Url.  This means the Url Master module can't determine the DNN page based on the Url.
            //    //In this case, it is up to this provider to identify the correct tabId that matches the Url.  Failure to do so will result in the incorrect tab being loaded when the page is rendered.
            //    if (tabId == -1)
            //    {
            //        siteRootMatch = true;
            //        if (_noDnnPagePathTabId > -1)
            //            //tabid -1 means a 'site root' match - meaning that the dnn page path wasn't included in the Url
            //            tabId = _noDnnPagePathTabId;//if tabid = -1, it means a site root match (no dnn page path) so we substitute in the tabid where this is being used
            //    }
            //    queryStringIndex = UrlController.GetQueryStringIndex(tabId, portalId, this, options, false);
            //    int i = 0;
            //    foreach (string urlParm in urlParms)
            //    {
            //        if (_urlPath != null && _urlPath.ToLower() == urlParm.ToLower())
            //        {
            //            //not this one, will be the next one

            //        }
            //        else
            //        {
            //            //check for existence of this value in the querystring index
            //            string qsKey = urlParm.ToLower();
            //            string qs = (string)queryStringIndex[qsKey];
            //            if (qs != null)
            //            {
            //                //found a querystring match
            //                found = true;
            //                messages.Add("Item Matched in Friendly Url Provider.  Url : " + urlParm + " Path : " + path);
            //                result += qs;
            //                break;
            //            }
            //        }
            //        //if we didn't match, then we will keep this parameter for the output querystring
            //        if (found == false)
            //            skipUpToIndex = i;
            //        i++;
            //    }

            //}

            ////put on any remainder of the path that wasn't to do with the friendly Url
            //string remainder = base.CreateQueryStringFromParameters(urlParms, skipUpToIndex);
            ////put it all together for the final rewrite string
            //result += remainder;

            return(result);
        }
Exemplo n.º 12
0
 /// <summary>
 /// This method is used by the Url Master Url Rewriting process.  The purpose of this method is to take the supplied array of Url parameters, and transform them into a module-specific querystring for the underlying re-written Url.
 /// </summary>
 /// <param name="urlParms">The array of parameters found after the DNN page path has been identified.  No key/valeu pairs are identified, the parameters are converted from the /key/value/key2/value2 format into [key,value,key2,value2] format.</param>
 /// <param name="tabId">TabId of identified DNN page. </param>
 /// <param name="portalId">PortalId of identified DNN portal.</param>
 /// <param name="options">The current Friendly Url options being used by the module.</param>
 /// <param name="cultureCode">Identified language/culture code, if supplied.</param>
 /// <param name="portalAlias">Identified portalAlias object for the request.</param>
 /// <param name="messages">List of debug messages.  Add to this list to help debug your module.  Can be viewed in the reponse headers of the request, or in the 'Test Url Rewriting' section of the Url Master module.</param>
 /// <param name="status">Out parameter, returns the Http status of the request.  May be 200,301,302, or 404.  For normal rewriting, return a 200 value.</param>
 /// <param name="location">If a 301 or 302 is returned in the status parameter, then this must contain a valid redirect location.  This should be a fully-qualified Url.</param>
 /// <returns>The querystring to be used for rewriting the Url. NOTE: doesn't need to include the tabid if the tabid parameter is > -1</returns>
 public override string TransformFriendlyUrlToQueryString(string[] urlParms, int tabId, int portalId, FriendlyUrlOptions options, string cultureCode, DotNetNuke.Entities.Portals.PortalAliasInfo portalAlias, ref List <string> messages, out int status, out string location)
 {
     //no rewriting for this provider
     location = null;
     status   = 200;
     return("");
 }