Exemplo n.º 1
0
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="httpContext">The HTTP context.</param>
        public void ProcessRequest(HttpContext httpContext)
        {
            string interactionDeviceType = InteractionDeviceType.GetClientType(httpContext.Request.UserAgent);

            try
            {
                CalendarProps calendarProps = ValidateRequestData(httpContext);

                if (calendarProps == null)
                {
                    return;
                }

                iCalendar icalendar = CreateICalendar(calendarProps, interactionDeviceType);

                iCalendarSerializer serializer = new iCalendarSerializer();
                string s = serializer.SerializeToString(icalendar);

                httpContext.Response.Clear();
                httpContext.Response.ClearHeaders();
                httpContext.Response.ClearContent();
                httpContext.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}_ical.ics", DateTime.Now.ToString("yyyy-MM-dd_hhmmss")));
                httpContext.Response.ContentType = "text/calendar";
                httpContext.Response.Write(s);
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, httpContext);
                SendBadRequest(httpContext);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Uses the Request information to determine if the device is mobile or not
        /// </summary>
        /// <returns>DevinedValueId for "Mobile" or "Computer", Mobile includes Tablet. Null if there is a data issue and the DefinedType is missing</returns>
        private int?GetDeviceTypeValueId()
        {
            // Get the device type Mobile or Computer
            DefinedTypeCache  definedTypeCache  = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.PERSONAL_DEVICE_TYPE.AsGuid());
            DefinedValueCache definedValueCache = null;

            var clientType = InteractionDeviceType.GetClientType(Request.UserAgent);

            clientType = clientType == "Mobile" || clientType == "Tablet" ? "Mobile" : "Computer";

            if (definedTypeCache != null)
            {
                definedValueCache = definedTypeCache.DefinedValues.FirstOrDefault(v => v.Value == clientType);

                if (definedValueCache == null)
                {
                    definedValueCache = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSONAL_DEVICE_TYPE_COMPUTER.AsGuid());
                }

                return(definedValueCache.Id);
            }

            return(null);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Execute method to write transaction to the database.
        /// </summary>
        public void Execute()
        {
            if (PageId.HasValue)
            {
                using (var rockContext = new RockContext())
                {
                    var userAgent = (this.UserAgent ?? string.Empty).Trim();
                    if (userAgent.Length > 450)
                    {
                        userAgent = userAgent.Substring(0, 450);   // trim super long useragents to fit in pageViewUserAgent.UserAgent
                    }

                    // get user agent info
                    var clientType = InteractionDeviceType.GetClientType(userAgent);

                    // don't log visits from crawlers
                    if (clientType != "Crawler")
                    {
                        // lookup the interaction channel, and create it if it doesn't exist
                        int channelMediumTypeValueId  = DefinedValueCache.Read(SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid()).Id;
                        var interactionChannelService = new InteractionChannelService(rockContext);
                        var interactionChannel        = interactionChannelService.Queryable()
                                                        .Where(a =>
                                                               a.ChannelTypeMediumValueId == channelMediumTypeValueId &&
                                                               a.ChannelEntityId == this.SiteId)
                                                        .FirstOrDefault();
                        if (interactionChannel == null)
                        {
                            interactionChannel      = new InteractionChannel();
                            interactionChannel.Name = SiteCache.Read(SiteId ?? 1).Name;
                            interactionChannel.ChannelTypeMediumValueId = channelMediumTypeValueId;
                            interactionChannel.ChannelEntityId          = this.SiteId;
                            interactionChannel.ComponentEntityTypeId    = EntityTypeCache.Read <Rock.Model.Page>().Id;
                            interactionChannelService.Add(interactionChannel);
                            rockContext.SaveChanges();
                        }

                        // check that the page exists as a component
                        var interactionComponent = new InteractionComponentService(rockContext).GetComponentByEntityId(interactionChannel.Id, PageId.Value, PageTitle);
                        rockContext.SaveChanges();

                        // Add the interaction
                        if (interactionComponent != null)
                        {
                            ClientInfo client        = uaParser.Parse(userAgent);
                            var        clientOs      = client.OS.ToString();
                            var        clientBrowser = client.UserAgent.ToString();

                            var interaction = new InteractionService(rockContext).AddInteraction(interactionComponent.Id, null, "View", Url, PersonAliasId, DateViewed,
                                                                                                 clientBrowser, clientOs, clientType, userAgent, IPAddress, this.SessionId?.AsGuidOrNull());

                            if (Url.IsNotNullOrWhitespace() && Url.IndexOf("utm_", StringComparison.OrdinalIgnoreCase) >= 0)
                            {
                                var urlParams = HttpUtility.ParseQueryString(Url);
                                interaction.Source   = urlParams.Get("utm_source").Truncate(25);
                                interaction.Medium   = urlParams.Get("utm_medium").Truncate(25);
                                interaction.Campaign = urlParams.Get("utm_campaign").Truncate(50);
                                interaction.Content  = urlParams.Get("utm_content").Truncate(50);
                            }

                            rockContext.SaveChanges();
                        }
                    }
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Execute method to write transaction to the database.
        /// </summary>
        public void Execute()
        {
            if (PageShortLinkId.HasValue)
            {
                using (var rockContext = new RockContext())
                {
                    var userAgent = (this.UserAgent ?? string.Empty).Trim();
                    if (userAgent.Length > 450)
                    {
                        userAgent = userAgent.Substring(0, 450);   // trim super long useragents to fit in pageViewUserAgent.UserAgent
                    }

                    // get user agent info
                    var clientType = InteractionDeviceType.GetClientType(userAgent);

                    // don't log visits from crawlers
                    if (clientType != "Crawler")
                    {
                        // lookup the interaction channel, and create it if it doesn't exist
                        int channelMediumTypeValueId = DefinedValueCache.Get(SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_URLSHORTENER.AsGuid()).Id;
                        InteractionChannelService interactionChannelService = new InteractionChannelService(rockContext);
                        var interactionChannel = interactionChannelService.Queryable()
                                                 .Where(a => a.ChannelTypeMediumValueId == channelMediumTypeValueId)
                                                 .FirstOrDefault();
                        if (interactionChannel == null)
                        {
                            interactionChannel      = new InteractionChannel();
                            interactionChannel.Name = "Short Links";
                            interactionChannel.ChannelTypeMediumValueId = channelMediumTypeValueId;
                            interactionChannel.ComponentEntityTypeId    = EntityTypeCache.Get <Rock.Model.PageShortLink>().Id;;
                            interactionChannel.Guid = SystemGuid.InteractionChannel.SHORT_LINKS.AsGuid();
                            interactionChannelService.Add(interactionChannel);
                            rockContext.SaveChanges();
                        }

                        // check that the page exists as a component
                        var interactionComponent = new InteractionComponentService(rockContext).GetComponentByEntityId(interactionChannel.Id, PageShortLinkId.Value, Token);
                        if (Url.IsNotNullOrWhiteSpace())
                        {
                            if (interactionComponent.ComponentSummary != Url)
                            {
                                interactionComponent.ComponentSummary = Url;
                            }

                            var urlDataJson = new { Url = Url }.ToJson();
                            if (interactionComponent.ComponentData != urlDataJson)
                            {
                                interactionComponent.ComponentData = urlDataJson;
                            }
                        }

                        rockContext.SaveChanges();

                        // Add the interaction
                        if (interactionComponent != null)
                        {
                            int?personAliasId = null;
                            if (UserName.IsNotNullOrWhiteSpace())
                            {
                                var currentUser = new UserLoginService(rockContext).GetByUserName(UserName);
                                personAliasId = currentUser?.Person?.PrimaryAlias?.Id;
                            }

                            ClientInfo client        = uaParser.Parse(userAgent);
                            var        clientOs      = client.OS.ToString();
                            var        clientBrowser = client.UserAgent.ToString();

                            new InteractionService(rockContext).AddInteraction(interactionComponent.Id, null, "View", Url, personAliasId, DateViewed,
                                                                               clientBrowser, clientOs, clientType, userAgent, IPAddress, this.SessionId?.AsGuidOrNull());
                            rockContext.SaveChanges();
                        }
                    }
                }
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Execute method to write transaction to the database.
        /// </summary>
        public void Execute()
        {
            if (!PageId.HasValue)
            {
                return;
            }

            var userAgent = (this.UserAgent ?? string.Empty).Trim();

            if (userAgent.Length > 450)
            {
                userAgent = userAgent.Substring(0, 450);   // trim super long useragents to fit in pageViewUserAgent.UserAgent
            }

            // get user agent info
            var clientType = InteractionDeviceType.GetClientType(userAgent);

            // don't log visits from crawlers
            if (clientType == "Crawler")
            {
                return;
            }

            using (var rockContext = new RockContext())
            {
                // lookup the interaction channel, and create it if it doesn't exist
                int channelMediumTypeValueId  = DefinedValueCache.Get(SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid()).Id;
                var interactionChannelService = new InteractionChannelService(rockContext);
                var interactionChannelId      = interactionChannelService.Queryable()
                                                .Where(a =>
                                                       a.ChannelTypeMediumValueId == channelMediumTypeValueId &&
                                                       a.ChannelEntityId == this.SiteId)
                                                .Select(a => ( int? )a.Id)
                                                .FirstOrDefault();
                if (interactionChannelId == null)
                {
                    var interactionChannel = new InteractionChannel();
                    interactionChannel.Name = SiteCache.Get(SiteId ?? 1).Name;
                    interactionChannel.ChannelTypeMediumValueId = channelMediumTypeValueId;
                    interactionChannel.ChannelEntityId          = this.SiteId;
                    interactionChannel.ComponentEntityTypeId    = EntityTypeCache.Get <Rock.Model.Page>().Id;
                    interactionChannelService.Add(interactionChannel);
                    rockContext.SaveChanges();
                    interactionChannelId = interactionChannel.Id;
                }

                // check that the page exists as a component
                var interactionComponent = new InteractionComponentService(rockContext).GetComponentByEntityId(interactionChannelId.Value, PageId.Value, PageTitle);
                if (interactionComponent.Id == 0)
                {
                    rockContext.SaveChanges();
                }

                // Add the interaction
                if (interactionComponent != null)
                {
                    var title = string.Empty;
                    if (BrowserTitle.IsNotNullOrWhiteSpace())
                    {
                        title = BrowserTitle;
                    }
                    else
                    {
                        title = PageTitle;
                    }

                    // remove site name from browser title
                    if (title.Contains("|"))
                    {
                        title = title.Substring(0, title.LastIndexOf('|')).Trim();
                    }

                    var interactionService = new InteractionService(rockContext);
                    var interaction        = interactionService.CreateInteraction(interactionComponent.Id, this.UserAgent, this.Url, this.IPAddress, this.SessionId.AsGuidOrNull());

                    interaction.EntityId            = null;
                    interaction.Operation           = "View";
                    interaction.InteractionSummary  = title;
                    interaction.InteractionData     = Url;
                    interaction.PersonAliasId       = PersonAliasId;
                    interaction.InteractionDateTime = DateViewed;
                    interactionService.Add(interaction);

                    rockContext.SaveChanges();
                }
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler" /> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            Guid?communicationGuid = context.Request.QueryString["c"].AsGuidOrNull();

            if (communicationGuid.HasValue)
            {
                var rockContext   = new RockContext();
                var communication = new CommunicationService(rockContext).Get(communicationGuid.Value);

                if (communication != null)
                {
                    var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);
                    mergeFields.Add("Communication", communication);

                    Person person = null;

                    string encodedKey = context.Request.QueryString["p"];
                    if (!string.IsNullOrWhiteSpace(encodedKey))
                    {
                        // first try and see if we can use the new GetByPersonActionIdentifier() otherwise
                        // fall-back to the old GetByImpersonationToken method.
                        var personService = new PersonService(rockContext);
                        person = personService.GetByPersonActionIdentifier(encodedKey, "Unsubscribe");
                        if (person == null)
                        {
                            // TODO: Support for trying via impersonation token should be removed once we get to Rock v11
                            person = personService.GetByImpersonationToken(encodedKey, true, null);
                        }
                    }

                    if (person == null)
                    {
                        var principal = context.User;
                        if (principal != null && principal.Identity != null)
                        {
                            var userLoginService = new Rock.Model.UserLoginService(new RockContext());
                            var userLogin        = userLoginService.GetByUserName(principal.Identity.Name);

                            if (userLogin != null)
                            {
                                var currentPerson = userLogin.Person;
                                // if a person wasn't specified in the URL, then only show it if the current person has EDIT auth to the communication
                                if (communication.IsAuthorized(Authorization.EDIT, currentPerson))
                                {
                                    person = currentPerson;
                                }
                            }
                        }
                    }

                    if (person != null)
                    {
                        mergeFields.Add("Person", person);

                        var recipient = new CommunicationRecipientService(rockContext).Queryable()
                                        .Where(r =>
                                               r.CommunicationId == communication.Id &&
                                               r.PersonAlias != null &&
                                               r.PersonAlias.PersonId == person.Id)
                                        .FirstOrDefault();

                        if (recipient != null)
                        {
                            // Add any additional merge fields created through a report
                            foreach (var mergeField in recipient.AdditionalMergeValues)
                            {
                                if (!mergeFields.ContainsKey(mergeField.Key))
                                {
                                    mergeFields.Add(mergeField.Key, mergeField.Value);
                                }
                            }
                        }

                        context.Response.ContentType = "text/html";
                        context.Response.Write(GetHtmlPreview(communication, mergeFields));

                        if (recipient != null)
                        {
                            // write an 'opened' interaction
                            var interactionService = new InteractionService(rockContext);

                            InteractionComponent interactionComponent = new InteractionComponentService(rockContext)
                                                                        .GetComponentByEntityId(Rock.SystemGuid.InteractionChannel.COMMUNICATION.AsGuid(),
                                                                                                communication.Id, communication.Subject);
                            rockContext.SaveChanges();

                            var ipAddress = Rock.Web.UI.RockPage.GetClientIpAddress();

                            var userAgent = context.Request.UserAgent ?? "";

                            UAParser.ClientInfo client = UAParser.Parser.GetDefault().Parse(userAgent);
                            var clientOs      = client.OS.ToString();
                            var clientBrowser = client.UA.ToString();
                            var clientType    = InteractionDeviceType.GetClientType(userAgent);

                            interactionService.AddInteraction(interactionComponent.Id, recipient.Id, "Opened", "", recipient.PersonAliasId, RockDateTime.Now, clientBrowser, clientOs, clientType, userAgent, ipAddress, null);

                            rockContext.SaveChanges();
                        }

                        return;
                    }
                }
            }

            context.Response.ContentType = "text/plain";
            context.Response.Write("Sorry, the communication you requested does not exist, or you are not authorized to view it.");
            return;
        }
        /// <summary>
        /// Unsubscribes the person from any lists that were selected.
        /// </summary>
        /// <returns>true if they were actually unsubscribed from something or false otherwise.</returns>
        private bool UnsubscribeFromLists()
        {
            if (_person == null)
            {
                return(false);
            }

            if (!cblUnsubscribeFromLists.SelectedValuesAsInt.Any())
            {
                nbUnsubscribeSuccessMessage.NotificationBoxType = NotificationBoxType.Warning;
                nbUnsubscribeSuccessMessage.Text    = "Please select the lists that you want to unsubscribe from.";
                nbUnsubscribeSuccessMessage.Visible = true;
                return(false);
            }

            List <Group> unsubscribedGroups = new List <Group>();
            var          rockContext        = new RockContext();

            foreach (var communicationListId in cblUnsubscribeFromLists.SelectedValuesAsInt)
            {
                // normally there would be at most 1 group member record for the person, but just in case, mark them all inactive
                var groupMemberRecordsForPerson = new GroupMemberService(rockContext).Queryable().Include(a => a.Group).Where(a => a.GroupId == communicationListId && a.PersonId == _person.Id);
                foreach (var groupMember in groupMemberRecordsForPerson.ToList())
                {
                    groupMember.GroupMemberStatus = GroupMemberStatus.Inactive;
                    if (groupMember.Note.IsNullOrWhiteSpace())
                    {
                        groupMember.Note = "Unsubscribed";
                    }

                    unsubscribedGroups.Add(groupMember.Group);

                    rockContext.SaveChanges();
                }

                // if they selected the CommunicationList associated with the CommunicationId from the Url, log an 'Unsubscribe' Interaction
                if (_communication != null && _communication.ListGroupId.HasValue && communicationListId == _communication.ListGroupId)
                {
                    var communicationRecipient = _communication.GetRecipientsQry(rockContext).Where(a => a.PersonAlias.PersonId == _person.Id).FirstOrDefault();
                    if (communicationRecipient != null)
                    {
                        var interactionService = new InteractionService(rockContext);

                        InteractionComponent interactionComponent = new InteractionComponentService(rockContext)
                                                                    .GetComponentByEntityId(Rock.SystemGuid.InteractionChannel.COMMUNICATION.AsGuid(), _communication.Id, _communication.Subject);

                        rockContext.SaveChanges();

                        var ipAddress = GetClientIpAddress();
                        var userAgent = Request.UserAgent ?? "";

                        UAParser.ClientInfo client = UAParser.Parser.GetDefault().Parse(userAgent);
                        var clientOs      = client.OS.ToString();
                        var clientBrowser = client.UA.ToString();
                        var clientType    = InteractionDeviceType.GetClientType(userAgent);

                        interactionService.AddInteraction(interactionComponent.Id, communicationRecipient.Id, "Unsubscribe", "", communicationRecipient.PersonAliasId, RockDateTime.Now, clientBrowser, clientOs, clientType, userAgent, ipAddress, null);

                        rockContext.SaveChanges();
                    }
                }
            }

            var mergeFields     = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
            int?communicationId = PageParameter(PageParameterKey.CommunicationId).AsIntegerOrNull();

            if (_communication != null)
            {
                mergeFields.Add("Communication", _communication);
            }

            mergeFields.Add("UnsubscribedGroups", unsubscribedGroups);

            nbUnsubscribeSuccessMessage.NotificationBoxType = NotificationBoxType.Success;
            nbUnsubscribeSuccessMessage.Text    = GetAttributeValue(AttributeKey.UnsubscribeSuccessText).ResolveMergeFields(mergeFields);
            nbUnsubscribeSuccessMessage.Visible = true;
            return(true);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Determine the logical page being requested by evaluating the routedata, or querystring and
        /// then loading the appropriate layout (ASPX) page
        ///
        /// Pick url on the following priority order:
        /// 1. PageId
        /// 2. Route match and site match
        /// 3. ShortLink match and site match
        /// 4. Route and no site match
        /// 5. ShortLink with no site match
        /// 6. If there is no routing info in the request then set to default page
        /// 7. 404 if route does not exist
        ///
        /// </summary>
        /// <param name="requestContext"></param>
        /// <returns></returns>
        System.Web.IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
        {
            string pageId      = string.Empty;
            int    routeId     = 0;
            bool   isSiteMatch = false;
            Dictionary <string, string> parms;
            string          host;
            HttpRequestBase routeHttpRequest;
            HttpCookie      siteCookie;

            // Context cannot be null
            if (requestContext == null)
            {
                throw new ArgumentNullException("requestContext");
            }

            try
            {
                routeHttpRequest = requestContext.HttpContext.Request;
                siteCookie       = routeHttpRequest.Cookies["last_site"];
                parms            = new Dictionary <string, string>();
                host             = WebRequestHelper.GetHostNameFromRequest(HttpContext.Current);

                if (requestContext.RouteData.Values["PageId"] != null)
                {
                    // Pages using the default routing URL will have the page id in the RouteData.Values collection
                    pageId      = ( string )requestContext.RouteData.Values["PageId"];
                    isSiteMatch = true;
                }
                else if (requestContext.RouteData.DataTokens["PageRoutes"] != null)
                {
                    SiteCache site = GetSite(routeHttpRequest, host, siteCookie);
                    // Pages that use a custom URL route will have the page id in the RouteData.DataTokens collection
                    GetPageIdFromDataTokens(requestContext, site, out pageId, out routeId, out isSiteMatch);

                    foreach (var routeParm in requestContext.RouteData.Values)
                    {
                        parms.Add(routeParm.Key, ( string )routeParm.Value);
                    }
                }
                else if (((System.Web.Routing.Route)requestContext.RouteData.Route).Url.IsNullOrWhiteSpace())
                {
                    // if we don't have routing info then set the page ID to the default page for the site.

                    // Get the site, if not found use the default site
                    SiteCache site = GetSite(routeHttpRequest, host, siteCookie);
                    if (site == null)
                    {
                        site = SiteCache.Get(SystemGuid.Site.SITE_ROCK_INTERNAL.AsGuid());
                    }

                    if (site.DefaultPageId.HasValue)
                    {
                        pageId      = site.DefaultPageId.Value.ToString();
                        isSiteMatch = true;
                    }
                    else
                    {
                        throw new SystemException("Invalid Site Configuration");
                    }
                }

                // If the the page ID and site has not yet been matched
                if (string.IsNullOrEmpty(pageId) || !isSiteMatch)
                {
                    SiteCache site = GetSite(routeHttpRequest, host, siteCookie);

                    // if not found use the default site
                    if (site == null)
                    {
                        site = SiteCache.Get(SystemGuid.Site.SITE_ROCK_INTERNAL.AsGuid());
                    }

                    if (site != null)
                    {
                        // Check to see if this is a short link route
                        string shortlink = null;
                        if (requestContext.RouteData.Values.ContainsKey("shortlink"))
                        {
                            shortlink = requestContext.RouteData.Values["shortlink"].ToString();
                        }

                        // If shortlink have the same name as route and route's site did not match, then check if shortlink site match.
                        if (shortlink.IsNullOrWhiteSpace() && requestContext.RouteData.DataTokens["RouteName"] != null)
                        {
                            shortlink = requestContext.RouteData.DataTokens["RouteName"].ToString();
                        }

                        if (shortlink.IsNotNullOrWhiteSpace())
                        {
                            using (var rockContext = new Rock.Data.RockContext())
                            {
                                var pageShortLink = new PageShortLinkService(rockContext).GetByToken(shortlink, site.Id);

                                if (pageShortLink != null && (pageShortLink.SiteId == site.Id || requestContext.RouteData.DataTokens["RouteName"] == null))
                                {
                                    pageId  = string.Empty;
                                    routeId = 0;

                                    string trimmedUrl = pageShortLink.Url.RemoveCrLf().Trim();

                                    var transaction = new ShortLinkTransaction();
                                    transaction.PageShortLinkId = pageShortLink.Id;
                                    transaction.Token           = pageShortLink.Token;
                                    transaction.Url             = trimmedUrl;
                                    if (requestContext.HttpContext.User != null)
                                    {
                                        transaction.UserName = requestContext.HttpContext.User.Identity.Name;
                                    }

                                    transaction.DateViewed = RockDateTime.Now;
                                    transaction.IPAddress  = WebRequestHelper.GetClientIpAddress(routeHttpRequest);
                                    transaction.UserAgent  = routeHttpRequest.UserAgent ?? string.Empty;
                                    RockQueue.TransactionQueue.Enqueue(transaction);

                                    requestContext.HttpContext.Response.Redirect(trimmedUrl);
                                    return(null);
                                }
                            }
                        }

                        // If site has has been enabled for mobile redirect, then we'll need to check what type of device is being used
                        if (site.EnableMobileRedirect)
                        {
                            // get the device type
                            string u = routeHttpRequest.UserAgent;

                            var clientType = InteractionDeviceType.GetClientType(u);

                            bool redirect = false;

                            // first check if device is a mobile device
                            if (clientType == "Mobile")
                            {
                                redirect = true;
                            }

                            // if not, mobile device and tables should be redirected also, check if device is a tablet
                            if (!redirect && site.RedirectTablets && clientType == "Tablet")
                            {
                                redirect = true;
                            }

                            if (redirect)
                            {
                                if (site.MobilePageId.HasValue)
                                {
                                    pageId  = site.MobilePageId.Value.ToString();
                                    routeId = 0;
                                }
                                else if (!string.IsNullOrWhiteSpace(site.ExternalUrl))
                                {
                                    requestContext.HttpContext.Response.Redirect(site.ExternalUrl);
                                    return(null);
                                }
                            }
                        }
                    }
                }

                PageCache page = null;
                if (!string.IsNullOrEmpty(pageId))
                {
                    int pageIdNumber = 0;
                    if (int.TryParse(pageId, out pageIdNumber))
                    {
                        page = PageCache.Get(pageIdNumber);
                    }
                }

                if (page == null)
                {
                    // try to get site's 404 page
                    SiteCache site = GetSite(routeHttpRequest, host, siteCookie);
                    if (site != null && site.PageNotFoundPageId != null)
                    {
                        if (Convert.ToBoolean(GlobalAttributesCache.Get().GetValue("Log404AsException")))
                        {
                            Rock.Model.ExceptionLogService.LogException(
                                new Exception($"404 Error: {routeHttpRequest.Url.AbsoluteUri}"),
                                requestContext.HttpContext.ApplicationInstance.Context);
                        }

                        page = PageCache.Get(site.PageNotFoundPageId ?? 0);
                        requestContext.HttpContext.Response.StatusCode             = 404;
                        requestContext.HttpContext.Response.TrySkipIisCustomErrors = true;
                    }
                    else
                    {
                        // no 404 page found for the site, return the default 404 error page
                        return((System.Web.UI.Page)BuildManager.CreateInstanceFromVirtualPath("~/Http404Error.aspx", typeof(System.Web.UI.Page)));
                    }
                }

                CreateOrUpdateSiteCookie(siteCookie, requestContext, page);

                string theme      = page.Layout.Site.Theme;
                string layout     = page.Layout.FileName;
                string layoutPath = PageCache.FormatPath(theme, layout);

                try
                {
                    return(CreateRockPage(page, layoutPath, routeId, parms, routeHttpRequest));
                }
                catch (System.Web.HttpException)
                {
                    // The Selected theme and/or layout didn't exist so try to use the layout in the default theme.
                    theme = "Rock";

                    // Verify that Layout exists in the default theme directory and if not try use the default layout of the default theme
                    string layoutPagePath = string.Format("~/Themes/Rock/Layouts/{0}.aspx", layout);
                    if (!File.Exists(requestContext.HttpContext.Server.MapPath(layoutPagePath)))
                    {
                        layout = "FullWidth";
                    }

                    layoutPath = PageCache.FormatPath(theme, layout);

                    return(CreateRockPage(page, layoutPath, routeId, parms, routeHttpRequest));
                }
            }
            catch (Exception ex)
            {
                if (requestContext.HttpContext != null)
                {
                    requestContext.HttpContext.Cache["RockExceptionOrder"] = "66";
                    requestContext.HttpContext.Cache["RockLastException"]  = ex;
                }

                return((System.Web.UI.Page)BuildManager.CreateInstanceFromVirtualPath("~/Error.aspx", typeof(System.Web.UI.Page)));
            }
        }
        /// <summary>
        /// Execute method to write transaction to the database.
        /// </summary>
        public void Execute()
        {
            // Dequeue any interactions that have been queued and not processed up to this point.
            var interactionTransactionInfos = new List <InteractionTransactionInfo>();

            while (InteractionInfoQueue.TryDequeue(out InteractionTransactionInfo interactionTransactionInfo))
            {
                interactionTransactionInfos.Add(interactionTransactionInfo);
            }

            if (!interactionTransactionInfos.Any())
            {
                // If all the interactions have been processed, exit.
                return;
            }

            // Get the distinct list of user agent strings within the interactions to be logged.
            var userAgentsLookup = interactionTransactionInfos.Where(a => a.UserAgent.IsNotNullOrWhiteSpace()).Select(a => a.UserAgent).Distinct().ToList().ToDictionary(a => a, v => InteractionDeviceType.GetClientType(v));

            // Include/exclude crawlers based on caller input.
            interactionTransactionInfos = interactionTransactionInfos.Where(a => a.LogCrawlers || a.UserAgent.IsNullOrWhiteSpace() || userAgentsLookup.GetValueOrNull(a.UserAgent) != "Crawler").ToList();

            if (!interactionTransactionInfos.Any())
            {
                // If there aren't interactions after considering whether to remove crawlers, exit.
                return;
            }

            using (var rockContext = new RockContext())
            {
                LogInteractions(interactionTransactionInfos, rockContext);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Determine the logical page being requested by evaluating the routedata, or querystring and
        /// then loading the appropriate layout (ASPX) page
        /// </summary>
        /// <param name="requestContext"></param>
        /// <returns></returns>
        System.Web.IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
        {
            if (requestContext == null)
            {
                throw new ArgumentNullException("requestContext");
            }

            try
            {
                var httpRequest = requestContext.HttpContext.Request;

                var siteCookie = httpRequest.Cookies["last_site"];

                string pageId  = "";
                int    routeId = 0;

                var parms = new Dictionary <string, string>();

                // Pages using the default routing URL will have the page id in the RouteData.Values collection
                if (requestContext.RouteData.Values["PageId"] != null)
                {
                    pageId = (string)requestContext.RouteData.Values["PageId"];
                }

                // Pages that use a custom URL route will have the page id in the RouteDate.DataTokens collection
                else if (requestContext.RouteData.DataTokens["PageRoutes"] != null)
                {
                    var pageAndRouteIds = requestContext.RouteData.DataTokens["PageRoutes"] as List <PageAndRouteId>;
                    if (pageAndRouteIds != null && pageAndRouteIds.Count > 0)
                    {
                        // Default to first site/page
                        if (pageAndRouteIds.Count >= 1)
                        {
                            var pageAndRouteId = pageAndRouteIds.First();
                            pageId  = pageAndRouteId.PageId.ToJson();
                            routeId = pageAndRouteId.RouteId;
                        }

                        // Then check to see if any can be matched by site
                        if (pageAndRouteIds.Count > 1)
                        {
                            SiteCache site = null;

                            // First check to see if site was specified in querystring
                            int?siteId = httpRequest.QueryString["SiteId"].AsIntegerOrNull();
                            if (siteId.HasValue)
                            {
                                site = SiteCache.Read(siteId.Value);
                            }

                            // Then check to see if site can be determined by domain
                            if (site == null)
                            {
                                site = SiteCache.GetSiteByDomain(httpRequest.Url.Host);
                            }

                            // Then check the last site
                            if (site == null)
                            {
                                if (siteCookie != null && siteCookie.Value != null)
                                {
                                    site = SiteCache.Read(siteCookie.Value.AsInteger());
                                }
                            }

                            if (site != null)
                            {
                                foreach (var pageAndRouteId in pageAndRouteIds)
                                {
                                    var pageCache = PageCache.Read(pageAndRouteId.PageId);
                                    if (pageCache != null && pageCache.Layout != null && pageCache.Layout.SiteId == site.Id)
                                    {
                                        pageId  = pageAndRouteId.PageId.ToJson();
                                        routeId = pageAndRouteId.RouteId;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    foreach (var routeParm in requestContext.RouteData.Values)
                    {
                        parms.Add(routeParm.Key, (string)routeParm.Value);
                    }
                }

                // If page has not been specified get the site by the domain and use the site's default page
                if (string.IsNullOrEmpty(pageId))
                {
                    SiteCache site = SiteCache.GetSiteByDomain(httpRequest.Url.Host);
                    if (site == null)
                    {
                        // Use last site
                        if (siteCookie != null && siteCookie.Value != null)
                        {
                            site = SiteCache.Read(siteCookie.Value.AsInteger());
                        }
                    }

                    // if not found use the default site
                    if (site == null)
                    {
                        site = SiteCache.Read(SystemGuid.Site.SITE_ROCK_INTERNAL.AsGuid());
                    }

                    if (site != null)
                    {
                        // Check to see if this is a short link route
                        if (requestContext.RouteData.Values.ContainsKey("shortlink"))
                        {
                            string shortlink = requestContext.RouteData.Values["shortlink"].ToString();
                            using (var rockContext = new Rock.Data.RockContext())
                            {
                                var pageShortLink = new PageShortLinkService(rockContext).GetByToken(shortlink, site.Id);
                                if (pageShortLink != null)
                                {
                                    string trimmedUrl = pageShortLink.Url.RemoveCrLf().Trim();

                                    var transaction = new ShortLinkTransaction();
                                    transaction.PageShortLinkId = pageShortLink.Id;
                                    transaction.Token           = pageShortLink.Token;
                                    transaction.Url             = trimmedUrl;
                                    if (requestContext.HttpContext.User != null)
                                    {
                                        transaction.UserName = requestContext.HttpContext.User.Identity.Name;
                                    }
                                    transaction.DateViewed = RockDateTime.Now;
                                    transaction.IPAddress  = UI.RockPage.GetClientIpAddress(httpRequest);
                                    transaction.UserAgent  = httpRequest.UserAgent ?? "";
                                    RockQueue.TransactionQueue.Enqueue(transaction);

                                    requestContext.HttpContext.Response.Redirect(trimmedUrl);
                                    return(null);
                                }
                            }
                        }

                        // If site has has been enabled for mobile redirect, then we'll need to check what type of device is being used
                        if (site.EnableMobileRedirect)
                        {
                            // get the device type
                            string u = httpRequest.UserAgent;

                            var clientType = InteractionDeviceType.GetClientType(u);

                            bool redirect = false;

                            // first check if device is a mobile device
                            if (clientType == "Mobile")
                            {
                                redirect = true;
                            }

                            // if not, mobile device and tables should be redirected also, check if device is a tablet
                            if (!redirect && site.RedirectTablets)
                            {
                                if (clientType == "Tablet")
                                {
                                    redirect = true;
                                }
                            }

                            if (redirect)
                            {
                                if (site.MobilePageId.HasValue)
                                {
                                    pageId = site.MobilePageId.Value.ToString();
                                }
                                else if (!string.IsNullOrWhiteSpace(site.ExternalUrl))
                                {
                                    requestContext.HttpContext.Response.Redirect(site.ExternalUrl);
                                    return(null);
                                }
                            }
                        }

                        if (string.IsNullOrWhiteSpace(pageId))
                        {
                            if (site.DefaultPageId.HasValue)
                            {
                                pageId = site.DefaultPageId.Value.ToString();
                            }

                            if (site.DefaultPageRouteId.HasValue)
                            {
                                routeId = site.DefaultPageRouteId.Value;
                            }
                        }
                    }

                    if (string.IsNullOrEmpty(pageId))
                    {
                        throw new SystemException("Invalid Site Configuration");
                    }
                }

                PageCache page = null;

                if (!string.IsNullOrEmpty(pageId))
                {
                    int pageIdNumber = 0;
                    if (Int32.TryParse(pageId, out pageIdNumber))
                    {
                        page = PageCache.Read(pageIdNumber);
                    }
                }

                if (page == null)
                {
                    // try to get site's 404 page
                    SiteCache site = SiteCache.GetSiteByDomain(httpRequest.Url.Host);
                    if (site == null)
                    {
                        // Use last site
                        if (siteCookie != null && siteCookie.Value != null)
                        {
                            site = SiteCache.Read(siteCookie.Value.AsInteger());
                        }
                    }

                    if (site != null && site.PageNotFoundPageId != null)
                    {
                        if (Convert.ToBoolean(GlobalAttributesCache.Read().GetValue("Log404AsException")))
                        {
                            Rock.Model.ExceptionLogService.LogException(
                                new Exception(string.Format("404 Error: {0}", httpRequest.Url.AbsoluteUri)),
                                requestContext.HttpContext.ApplicationInstance.Context);
                        }

                        page = PageCache.Read(site.PageNotFoundPageId ?? 0);
                    }
                    else
                    {
                        // no 404 page found for the site, return the default 404 error page
                        return((System.Web.UI.Page)BuildManager.CreateInstanceFromVirtualPath("~/Http404Error.aspx", typeof(System.Web.UI.Page)));
                    }
                }

                string theme      = page.Layout.Site.Theme;
                string layout     = page.Layout.FileName;
                string layoutPath = PageCache.FormatPath(theme, layout);

                if (siteCookie == null)
                {
                    siteCookie = new System.Web.HttpCookie("last_site", page.Layout.SiteId.ToString());
                }
                else
                {
                    siteCookie.Value = page.Layout.SiteId.ToString();
                }
                requestContext.HttpContext.Response.SetCookie(siteCookie);

                try
                {
                    // Return the page for the selected theme and layout
                    Rock.Web.UI.RockPage cmsPage = (Rock.Web.UI.RockPage)BuildManager.CreateInstanceFromVirtualPath(layoutPath, typeof(Rock.Web.UI.RockPage));
                    cmsPage.SetPage(page);
                    cmsPage.PageReference = new PageReference(page.Id, routeId, parms, httpRequest.QueryString);
                    return(cmsPage);
                }
                catch (System.Web.HttpException)
                {
                    // The Selected theme and/or layout didn't exist, attempt first to use the layout in the default theme.
                    theme = "Rock";

                    // If not using the default layout, verify that Layout exists in the default theme directory
                    if (layout != "FullWidth" &&
                        !File.Exists(requestContext.HttpContext.Server.MapPath(string.Format("~/Themes/Rock/Layouts/{0}.aspx", layout))))
                    {
                        // If selected layout doesn't exist in the default theme, switch to the Default layout
                        layout = "FullWidth";
                    }

                    // Build the path to the aspx file to
                    layoutPath = PageCache.FormatPath(theme, layout);

                    // Return the default layout and/or theme
                    Rock.Web.UI.RockPage cmsPage = (Rock.Web.UI.RockPage)BuildManager.CreateInstanceFromVirtualPath(layoutPath, typeof(Rock.Web.UI.RockPage));
                    cmsPage.SetPage(page);
                    cmsPage.PageReference = new PageReference(page.Id, routeId, parms, httpRequest.QueryString);
                    return(cmsPage);
                }
            }
            catch (Exception ex)
            {
                if (requestContext.HttpContext != null)
                {
                    requestContext.HttpContext.Cache["RockExceptionOrder"] = "66";
                    requestContext.HttpContext.Cache["RockLastException"]  = ex;
                }

                System.Web.UI.Page errorPage = (System.Web.UI.Page)BuildManager.CreateInstanceFromVirtualPath("~/Error.aspx", typeof(System.Web.UI.Page));
                return(errorPage);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Determine the logical page being requested by evaluating the routedata, or querystring and
        /// then loading the appropriate layout (ASPX) page
        ///
        /// Pick url on the following priority order:
        /// 1. PageId
        /// 2. Route match and site match
        /// 3. ShortLink match and site match
        /// 4. Route and no site match
        /// 5. ShortLink with no site match
        /// 6. If there is no routing info in the request then set to default page
        /// 7. 404 if route does not exist
        ///
        /// </summary>
        /// <param name="requestContext"></param>
        /// <returns></returns>
        System.Web.IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
        {
            string pageId      = string.Empty;
            int    routeId     = 0;
            bool   isSiteMatch = false;
            Dictionary <string, string> parms;
            string          host;
            HttpRequestBase routeHttpRequest;
            HttpCookie      siteCookie;
            SiteCache       site;

            // Context cannot be null
            if (requestContext == null)
            {
                throw new ArgumentNullException("requestContext");
            }

            try
            {
                routeHttpRequest = requestContext.HttpContext.Request;
                siteCookie       = routeHttpRequest.Cookies["last_site"];
                parms            = new Dictionary <string, string>();
                host             = WebRequestHelper.GetHostNameFromRequest(HttpContext.Current);
                site             = GetSite(host, siteCookie);

                if (requestContext.RouteData.Values["PageId"] != null)
                {
                    // Pages using the default routing URL will have the page id in the RouteData.Values collection
                    pageId = ( string )requestContext.RouteData.Values["PageId"];

                    // Does the page ID exist on the requesting site
                    isSiteMatch = IsSiteMatch(site, pageId.AsIntegerOrNull());

                    if (site != null && site.EnableExclusiveRoutes && !isSiteMatch)
                    {
                        // If the site has to match and does not then don't use the page ID. Set it to empty so the 404 can be returned.
                        pageId = string.Empty;
                    }
                    else if (!isSiteMatch)
                    {
                        // This page belongs to another site, make sure it is allowed to be loaded.
                        if (IsPageExclusiveToAnotherSite(site, pageId.AsIntegerOrNull(), null))
                        {
                            // If the page has to match the site and does not then don't use the page ID. Set it to empty so the 404 can be returned.
                            pageId = string.Empty;
                        }
                    }
                }
                else if (requestContext.RouteData.DataTokens["PageRoutes"] != null)
                {
                    // Pages that use a custom URL route will have the page id in the RouteData.DataTokens collection
                    GetPageIdFromDataTokens(requestContext, site, out pageId, out routeId, out isSiteMatch);

                    foreach (var routeParm in requestContext.RouteData.Values)
                    {
                        parms.Add(routeParm.Key, ( string )routeParm.Value);
                    }
                }
                else if (((System.Web.Routing.Route)requestContext.RouteData.Route).Url.IsNullOrWhiteSpace())
                {
                    // if we don't have routing info then set the page ID to the default page for the site.

                    // Get the site, if not found use the default site
                    if (site == null)
                    {
                        site = SiteCache.Get(SystemGuid.Site.SITE_ROCK_INTERNAL.AsGuid());
                    }

                    if (site.DefaultPageId.HasValue)
                    {
                        pageId      = site.DefaultPageId.Value.ToString();
                        isSiteMatch = true;
                    }
                    else
                    {
                        throw new SystemException("Invalid Site Configuration");
                    }
                }

                // If the the page ID and site has not yet been matched
                if (string.IsNullOrEmpty(pageId) || !isSiteMatch)
                {
                    // if not found use the default site
                    if (site == null)
                    {
                        site = SiteCache.Get(SystemGuid.Site.SITE_ROCK_INTERNAL.AsGuid());
                    }

                    // Are shortlinks enabled for this site? If so, check for a matching shortlink route.
                    if (site != null)
                    {
                        if (site.EnabledForShortening)
                        {
                            // Check to see if this is a short link route
                            string shortlink = null;
                            if (requestContext.RouteData.Values.ContainsKey("shortlink"))
                            {
                                shortlink = requestContext.RouteData.Values["shortlink"].ToString();
                            }
                            else
                            {
                                // Because we implemented shortlinks using a {shortlink} (catchall) route, it's
                                // possible the organization added a custom {catchall} route (at root level; no slashes)
                                // and it is overriding our shortlink route.  If they did, use it for a possible 'shortlink'
                                // route match.
                                if (requestContext.RouteData.DataTokens["RouteName"] != null && requestContext.RouteData.DataTokens["RouteName"].ToStringSafe().StartsWith("{"))
                                {
                                    var routeName = requestContext.RouteData.DataTokens["RouteName"].ToStringSafe().Trim(new Char[] { '{', '}' });
                                    shortlink = requestContext.RouteData.Values[routeName].ToStringSafe();
                                }
                            }

                            if (shortlink.IsNullOrWhiteSpace() && requestContext.RouteData.DataTokens["RouteName"] != null)
                            {
                                shortlink = requestContext.RouteData.DataTokens["RouteName"].ToString();
                            }

                            if (shortlink.IsNotNullOrWhiteSpace())
                            {
                                using (var rockContext = new Rock.Data.RockContext())
                                {
                                    var pageShortLink = new PageShortLinkService(rockContext).GetByToken(shortlink, site.Id);

                                    // Use the short link if the site IDs match or the current site and shortlink site are not exclusive.
                                    // Note: this is only a restriction based on the site chosen as the owner of the shortlink, the acutal URL can go anywhere.
                                    if (pageShortLink != null && (pageShortLink.SiteId == site.Id || (!site.EnableExclusiveRoutes && !pageShortLink.Site.EnableExclusiveRoutes)))
                                    {
                                        if (pageShortLink.SiteId == site.Id || requestContext.RouteData.DataTokens["RouteName"] == null)
                                        {
                                            pageId  = string.Empty;
                                            routeId = 0;

                                            string trimmedUrl = pageShortLink.Url.RemoveCrLf().Trim();

                                            var transaction = new ShortLinkTransaction
                                            {
                                                PageShortLinkId = pageShortLink.Id,
                                                Token           = pageShortLink.Token,
                                                Url             = trimmedUrl,
                                                DateViewed      = RockDateTime.Now,
                                                IPAddress       = WebRequestHelper.GetClientIpAddress(routeHttpRequest),
                                                UserAgent       = routeHttpRequest.UserAgent ?? string.Empty,
                                                UserName        = requestContext.HttpContext.User?.Identity.Name
                                            };

                                            RockQueue.TransactionQueue.Enqueue(transaction);

                                            requestContext.HttpContext.Response.Redirect(trimmedUrl, false);
                                            requestContext.HttpContext.ApplicationInstance.CompleteRequest();

                                            // Global.asax.cs will throw and log an exception if null is returned, so just return a new page.
                                            return(new System.Web.UI.Page());
                                        }
                                    }
                                }
                            }
                        }

                        // If site has has been enabled for mobile redirect, then we'll need to check what type of device is being used
                        if (site.EnableMobileRedirect)
                        {
                            // get the device type
                            string u = routeHttpRequest.UserAgent;

                            var clientType = InteractionDeviceType.GetClientType(u);

                            bool redirect = false;

                            // first check if device is a mobile device
                            if (clientType == "Mobile")
                            {
                                redirect = true;
                            }

                            // if not, mobile device and tables should be redirected also, check if device is a tablet
                            if (!redirect && site.RedirectTablets && clientType == "Tablet")
                            {
                                redirect = true;
                            }

                            if (redirect)
                            {
                                if (site.MobilePageId.HasValue)
                                {
                                    pageId  = site.MobilePageId.Value.ToString();
                                    routeId = 0;
                                }
                                else if (!string.IsNullOrWhiteSpace(site.ExternalUrl))
                                {
                                    requestContext.HttpContext.Response.Redirect(site.ExternalUrl, false);
                                    requestContext.HttpContext.ApplicationInstance.CompleteRequest();

                                    // Global.asax.cs will throw and log an exception if null is returned, so just return a new page.
                                    return(new System.Web.UI.Page());
                                }
                            }
                        }
                    }
                }

                PageCache page = null;
                if (!string.IsNullOrEmpty(pageId))
                {
                    int pageIdNumber = 0;
                    if (int.TryParse(pageId, out pageIdNumber))
                    {
                        page = PageCache.Get(pageIdNumber);
                    }
                }

                if (page == null)
                {
                    // try to get site's 404 page
                    if (site != null && site.PageNotFoundPageId != null)
                    {
                        if (Convert.ToBoolean(GlobalAttributesCache.Get().GetValue("Log404AsException")))
                        {
                            Rock.Model.ExceptionLogService.LogException(
                                new Exception($"404 Error: {routeHttpRequest.Url.AbsoluteUri}"),
                                requestContext.HttpContext.ApplicationInstance.Context);
                        }

                        page = PageCache.Get(site.PageNotFoundPageId ?? 0);
                        requestContext.HttpContext.Response.StatusCode             = 404;
                        requestContext.HttpContext.Response.TrySkipIisCustomErrors = true;
                    }
                    else
                    {
                        // no 404 page found for the site, return the default 404 error page
                        return((System.Web.UI.Page)BuildManager.CreateInstanceFromVirtualPath("~/Http404Error.aspx", typeof(System.Web.UI.Page)));
                    }
                }

                CreateOrUpdateSiteCookie(siteCookie, requestContext, page);

                string theme      = page.Layout.Site.Theme;
                string layout     = page.Layout.FileName;
                string layoutPath = PageCache.FormatPath(theme, layout);

                try
                {
                    return(CreateRockPage(page, layoutPath, routeId, parms, routeHttpRequest));
                }
                catch (System.Web.HttpException)
                {
                    // The Selected theme and/or layout didn't exist so try to use the layout in the default theme.
                    theme = "Rock";

                    // Verify that Layout exists in the default theme directory and if not try use the default layout of the default theme
                    string layoutPagePath = string.Format("~/Themes/Rock/Layouts/{0}.aspx", layout);
                    if (!File.Exists(requestContext.HttpContext.Server.MapPath(layoutPagePath)))
                    {
                        layout = "FullWidth";
                    }

                    layoutPath = PageCache.FormatPath(theme, layout);

                    return(CreateRockPage(page, layoutPath, routeId, parms, routeHttpRequest));
                }
            }
            catch (Exception ex)
            {
                if (requestContext.HttpContext != null)
                {
                    requestContext.HttpContext.Cache["RockExceptionOrder"] = "66";
                    requestContext.HttpContext.Cache["RockLastException"]  = ex;
                }

                return((System.Web.UI.Page)BuildManager.CreateInstanceFromVirtualPath("~/Error.aspx", typeof(System.Web.UI.Page)));
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Execute method to write transaction to the database.
        /// </summary>
        public void Execute()
        {
            using ( var rockContext = new RockContext() )
            {

                var userAgent = (this.UserAgent ?? string.Empty).Trim();
                if ( userAgent.Length > 450 )
                {
                    userAgent = userAgent.Substring( 0, 450 ); // trim super long useragents to fit in pageViewUserAgent.UserAgent
                }

                // get user agent info
                var clientType = PageViewUserAgent.GetClientType( userAgent );

                // don't log visits from crawlers
                if ( clientType != "Crawler" )
                {
                    InteractionChannelService interactionChannelService = new InteractionChannelService( rockContext );
                    InteractionComponentService interactionComponentService = new InteractionComponentService( rockContext );
                    InteractionDeviceTypeService interactionDeviceTypeService = new InteractionDeviceTypeService( rockContext );
                    InteractionSessionService interactionSessionService = new InteractionSessionService( rockContext );
                    InteractionService interactionService = new InteractionService( rockContext );

                    ClientInfo client = uaParser.Parse( userAgent );
                    var clientOs = client.OS.ToString();
                    var clientBrowser = client.UserAgent.ToString();

                    // lookup the interactionDeviceType, and create it if it doesn't exist
                    var interactionDeviceType = interactionDeviceTypeService.Queryable().Where( a => a.Application == clientBrowser
                                                && a.OperatingSystem == clientOs && a.ClientType == clientType ).FirstOrDefault();

                    if ( interactionDeviceType == null )
                    {
                        interactionDeviceType = new InteractionDeviceType();
                        interactionDeviceType.DeviceTypeData = userAgent;
                        interactionDeviceType.ClientType = clientType;
                        interactionDeviceType.OperatingSystem = clientOs;
                        interactionDeviceType.Application = clientBrowser;
                        interactionDeviceType.Name = string.Format( "{0} - {1}", clientOs, clientBrowser );
                        interactionDeviceTypeService.Add( interactionDeviceType );
                        rockContext.SaveChanges();
                    }

                    // lookup interactionSession, and create it if it doesn't exist
                    Guid sessionId = this.SessionId.AsGuid();
                    int? interactionSessionId = interactionSessionService.Queryable()
                                                    .Where(
                                                        a => a.DeviceTypeId == interactionDeviceType.Id
                                                        && a.Guid == sessionId )
                                                    .Select( a => (int?)a.Id )
                                                    .FirstOrDefault();

                    if ( !interactionSessionId.HasValue )
                    {
                        var interactionSession = new InteractionSession();
                        interactionSession.DeviceTypeId = interactionDeviceType.Id;
                        interactionSession.IpAddress = this.IPAddress;
                        interactionSession.Guid = sessionId;
                        interactionSessionService.Add( interactionSession );
                        rockContext.SaveChanges();
                        interactionSessionId = interactionSession.Id;
                    }

                    int componentEntityTypeId = EntityTypeCache.Read<Rock.Model.Page>().Id;
                    string siteName = SiteCache.Read( SiteId ?? 1 ).Name;

                    // lookup the interaction channel, and create it if it doesn't exist
                    int channelMediumTypeValueId = DefinedValueCache.Read( SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid() ).Id;

                    // check that the site exists as a channel
                    var interactionChannel = interactionChannelService.Queryable()
                                                        .Where( a =>
                                                            a.ChannelTypeMediumValueId == channelMediumTypeValueId
                                                            && a.ChannelEntityId == this.SiteId )
                                                        .FirstOrDefault();
                    if ( interactionChannel == null )
                    {
                        interactionChannel = new InteractionChannel();
                        interactionChannel.Name = siteName;
                        interactionChannel.ChannelTypeMediumValueId = channelMediumTypeValueId;
                        interactionChannel.ChannelEntityId = this.SiteId;
                        interactionChannel.ComponentEntityTypeId = componentEntityTypeId;
                        interactionChannelService.Add( interactionChannel );
                        rockContext.SaveChanges();
                    }

                    // check that the page exists as a component
                    var interactionComponent = interactionComponentService.Queryable()
                                                        .Where( a =>
                                                            a.EntityId == PageId
                                                            && a.ChannelId == interactionChannel.Id )
                                                        .FirstOrDefault();
                    if ( interactionComponent == null )
                    {
                        interactionComponent = new InteractionComponent();
                        interactionComponent.Name = PageTitle;
                        interactionComponent.EntityId = PageId;
                        interactionComponent.ChannelId = interactionChannel.Id;
                        interactionComponentService.Add( interactionComponent );
                        rockContext.SaveChanges();
                    }

                    // add the interaction
                    Interaction interaction = new Interaction();
                    interactionService.Add( interaction );

                    // obfuscate rock magic token
                    Regex rgx = new Regex( @"rckipid=([^&]*)" );
                    string cleanUrl = rgx.Replace( this.Url, "rckipid=XXXXXXXXXXXXXXXXXXXXXXXXXXXX" );

                    interaction.InteractionData = cleanUrl;
                    interaction.Operation = "View";
                    interaction.PersonAliasId = this.PersonAliasId;
                    interaction.InteractionDateTime = this.DateViewed;
                    interaction.InteractionSessionId = interactionSessionId;
                    interaction.InteractionComponentId = interactionComponent.Id;
                    rockContext.SaveChanges();
                }
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Execute method to write transaction to the database.
        /// </summary>
        public void Execute()
        {
            if (!this._logInteraction || InteractionSummary.IsNullOrWhiteSpace())
            {
                return;
            }

            if (!this.LogCrawlers)
            {
                // get user agent info
                var clientType = InteractionDeviceType.GetClientType(_userAgent);
                // don't log visits from crawlers
                if (clientType == "Crawler")
                {
                    return;
                }
            }

            var rockContext = new RockContext();

            // lookup the interaction channel, and create it if it doesn't exist
            var interactionChannelService = new InteractionChannelService(rockContext);
            var interactionChannelId      = interactionChannelService.Queryable()
                                            .Where(a =>
                                                   a.ChannelTypeMediumValueId == _channelMediumTypeValue.Id &&
                                                   a.ChannelEntityId == _channelEntityId)
                                            .Select(a => ( int? )a.Id)
                                            .FirstOrDefault();

            if (interactionChannelId == null)
            {
                var interactionChannel = new InteractionChannel();
                interactionChannel.Name = _channelName;
                interactionChannel.ChannelTypeMediumValueId = _channelMediumTypeValue.Id;
                interactionChannel.ChannelEntityId          = _channelEntityId;
                interactionChannel.ComponentEntityTypeId    = _componentEntityTypeId;
                interactionChannelService.Add(interactionChannel);
                rockContext.SaveChanges();
                interactionChannelId = interactionChannel.Id;
            }

            // check that the contentChannelItem exists as a component
            var interactionComponent = new InteractionComponentService(rockContext).GetComponentByEntityId(interactionChannelId.Value, _componentEntityId, _componentName);

            rockContext.SaveChanges();

            // Add the interaction
            if (interactionComponent != null)
            {
                var interactionService = new InteractionService(rockContext);
                var interaction        = interactionService.CreateInteraction(interactionComponent.Id, _userAgent, _url, _ipAddress, _browserSessionId);

                interaction.EntityId            = null;
                interaction.Operation           = "View";
                interaction.InteractionSummary  = InteractionSummary;
                interaction.InteractionData     = _url;
                interaction.PersonAliasId       = CurrentPersonAliasId;
                interaction.InteractionDateTime = RockDateTime.Now;
                interactionService.Add(interaction);
                rockContext.SaveChanges();
            }
        }
        // Handlers

        private System.Web.IHttpHandler GetHandlerForPage(RequestContext requestContext, PageCache page, int routeId = 0, bool checkMobile = true)
        {
            var site = page.Layout.Site;

            // Check for a mobile redirect on the site
            if (checkMobile && site.EnableMobileRedirect)
            {
                var clientType = InteractionDeviceType.GetClientType(requestContext.HttpContext.Request.UserAgent);

                if (clientType == "Mobile" || (site.RedirectTablets && clientType == "Tablet"))
                {
                    if (site.MobilePageId.HasValue)
                    {
                        var mobilePage = PageCache.Get(site.MobilePageId.Value);
                        if (mobilePage != null)
                        {
                            return(GetHandlerForPage(requestContext, mobilePage, routeId, false));
                        }
                    }
                    else if (!string.IsNullOrWhiteSpace(site.ExternalUrl))
                    {
                        requestContext.HttpContext.Response.Redirect(site.ExternalUrl);
                        return(null);
                    }
                }
            }

            // Set the last site cookie
            var siteCookie = requestContext.HttpContext.Request.Cookies["last_site"];

            if (siteCookie == null)
            {
                siteCookie = new System.Web.HttpCookie("last_site", page.Layout.SiteId.ToString());
            }
            else
            {
                siteCookie.Value = page.Layout.SiteId.ToString();
            }
            requestContext.HttpContext.Response.SetCookie(siteCookie);

            // Get the Layout & Theme Details
            string theme      = page.Layout.Site.Theme;
            string layout     = page.Layout.FileName;
            string layoutPath = PageCache.FormatPath(theme, layout);

            // Get any route parameters
            var parms = new Dictionary <string, string>();

            foreach (var routeParm in requestContext.RouteData.Values)
            {
                if (routeParm.Key != "PageId")
                {
                    parms.Add(routeParm.Key, (string)routeParm.Value);
                }
            }

            try
            {
                // Return the page for the selected theme and layout
                Rock.Web.UI.RockPage cmsPage = (Rock.Web.UI.RockPage)BuildManager.CreateInstanceFromVirtualPath(layoutPath, typeof(Rock.Web.UI.RockPage));
                cmsPage.SetPage(page);
                cmsPage.PageReference = new PageReference(page.Id, routeId, parms, requestContext.HttpContext.Request.QueryString);
                return(cmsPage);
            }
            catch (System.Web.HttpException)
            {
                // The Selected theme and/or layout didn't exist, attempt first to use the layout in the default theme.
                theme = "Rock";

                // If not using the default layout, verify that Layout exists in the default theme directory
                if (layout != "FullWidth" &&
                    !File.Exists(requestContext.HttpContext.Server.MapPath(string.Format("~/Themes/Rock/Layouts/{0}.aspx", layout))))
                {
                    // If selected layout doesn't exist in the default theme, switch to the Default layout
                    layout = "FullWidth";
                }

                // Build the path to the aspx file to
                layoutPath = PageCache.FormatPath(theme, layout);

                // Return the default layout and/or theme
                Rock.Web.UI.RockPage cmsPage = (Rock.Web.UI.RockPage)BuildManager.CreateInstanceFromVirtualPath(layoutPath, typeof(Rock.Web.UI.RockPage));
                cmsPage.SetPage(page);
                cmsPage.PageReference = new PageReference(page.Id, routeId, parms, requestContext.HttpContext.Request.QueryString);
                return(cmsPage);
            }
        }
Exemplo n.º 15
0
        private void ShowCommunication()
        {
            pnlViewMessage.Visible = true;

            var communicationGuid = PageParameter("c").AsGuid();

            var    rockContext          = new RockContext();
            var    communicationService = new CommunicationService(rockContext);
            var    personService        = new PersonService(rockContext);
            Person person = null;

            if (PageParameter("p").IsNotNullOrWhiteSpace())
            {
                person = personService.GetByImpersonationToken(PageParameter("p"), true, null);
            }

            if (person == null)
            {
                person = CurrentPerson;
            }

            var communication = communicationService.Get(communicationGuid);

            if (communication == null || !communication.Recipients.Where(r => r.PersonAlias.PersonId == person.Id).Any())
            {
                var message = "<div class='alert alert-info'>This message is currently unavailable</div>";
                lMessageContent.Text = message;

                return;
            }

            var recipient   = communication.Recipients.Where(r => r.PersonAlias.PersonId == person.Id).FirstOrDefault();
            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);

            mergeFields.Add("Communication", "communication");
            mergeFields.Add("Person", person);

            foreach (var mergeField in recipient.AdditionalMergeValues)
            {
                if (!mergeFields.ContainsKey(mergeField.Key))
                {
                    mergeFields.Add(mergeField.Key, mergeField.Value);
                }
            }

            string body = communication.Message.ResolveMergeFields(mergeFields, communication.EnabledLavaCommands);

            body = System.Text.RegularExpressions.Regex.Replace(body, @"\[\[\s*UnsubscribeOption\s*\]\]", string.Empty);
            lMessageContent.Text = body;


            // write an 'opened' interaction
            var interactionService = new InteractionService(rockContext);

            InteractionComponent interactionComponent = new InteractionComponentService(rockContext)
                                                        .GetComponentByEntityId(Rock.SystemGuid.InteractionChannel.COMMUNICATION.AsGuid(),
                                                                                communication.Id, communication.Subject);

            rockContext.SaveChanges();

            var ipAddress = Rock.Web.UI.RockPage.GetClientIpAddress();

            var userAgent = Request.UserAgent ?? "";

            UAParser.ClientInfo client = UAParser.Parser.GetDefault().Parse(userAgent);
            var clientOs      = client.OS.ToString();
            var clientBrowser = client.UA.ToString();
            var clientType    = InteractionDeviceType.GetClientType(userAgent);

            interactionService.AddInteraction(interactionComponent.Id, recipient.Id, "Opened", "", recipient.PersonAliasId, RockDateTime.Now, clientBrowser, clientOs, clientType, userAgent, ipAddress, null);

            rockContext.SaveChanges();
        }