/// <summary> /// Get a list of expiring pages expiring soon, or due never to expire /// </summary> /// <param name="inTheNextHowManyDays"> /// How many days to look forward /// </param> public IEnumerable <UmbracoPage> GetExpiringPages(int inTheNextHowManyDays) { // if the node is expiring within the declared period, add it to the list // if the node has a null expire date and is published, also add it to the list as it is a never expiring page // (Note: This should be the External index, so all results are published nodes) var query = _examineSearcher.CreateSearchCriteria(Examine.SearchCriteria.BooleanOperation.Or); query.Range("expireDate", DateTime.Today, DateTime.Today.AddDays(inTheNextHowManyDays)).Or().Field("expireDate", "99991231235959"); // Sorting using Examine would be faster but was not working, so sort the results in .NET var expiringNodes = _examineSearcher.Search(query).OrderBy(result => result.Fields["expireDate"].ToString()); var pages = new List <UmbracoPage>(); foreach (var expiringNode in expiringNodes) { var page = new UmbracoPage { PageId = Int32.Parse(expiringNode.Fields["__NodeId"], CultureInfo.InvariantCulture), PageName = expiringNode.Fields["nodeName"], PagePath = expiringNode.Fields["path"] }; page.PageUrl = _umbracoHelper.NiceUrl(page.PageId); if (expiringNode.Fields["expireDate"] != "99991231235959") { var expireDate = expiringNode.Fields["expireDate"].ToString(); page.ExpiryDate = new DateTime(Int32.Parse(expireDate.Substring(0, 4)), Int32.Parse(expireDate.Substring(4, 2)), Int32.Parse(expireDate.Substring(6, 2)), Int32.Parse(expireDate.Substring(8, 2)), Int32.Parse(expireDate.Substring(10, 2)), Int32.Parse(expireDate.Substring(12, 2))); } pages.Add(page); } return(pages); }
/// <summary> /// Returns user right menu /// </summary> /// <returns>Hierarchical menu list</returns> public IEnumerable <MemberCenterMenuItem> GetRightMenu() { // Get menu collection root node var rootNode = ((DynamicPublishedContent)_umbracoHelper.ContentAtRoot().First()) .DescendantsOrSelf("MemberCenterRightMenuCollection").First(); // Get the list of all menu items that have proper user rights // List has flat structure, next step is to build hierarchy var flatList = ((DynamicPublishedContent)_umbracoHelper.ContentAtRoot().First()) .Descendants("MemberCenterRightMenuItem") .Where(UserHasAccess) .Select(_ => new MemberCenterMenuItem() { Id = _.Id, ParentId = _.Parent.Id, Title = _.Name, Url = _umbracoHelper.NiceUrl(_.GetPropertyValue <int>("pageLink")), Description = _.GetPropertyValue <string>("description") }); // Build hierarchical menu // Show items that have subitems or description // Empty items will be skiped var result = BuildMenuTree(rootNode.Id, flatList) .Where(_ => _.Items.Any() || !String.IsNullOrEmpty(_.Description)); return(result); }
/// <summary> /// Returns a collection of entities for content based on search results /// </summary> /// <param name="umbracoHelper"></param> /// <param name="results"></param> /// <returns></returns> private IEnumerable <SearchResultItem> ContentFromSearchResults(UmbracoHelper umbracoHelper, IEnumerable <SearchResult> results) { var mapped = Mapper.Map <IEnumerable <SearchResultItem> >(results).ToArray(); //add additional data foreach (var m in mapped) { var intId = m.Id.TryConvertTo <int>(); if (intId.Success) { m.AdditionalData["Url"] = umbracoHelper.NiceUrl(intId.Result); } } return(mapped); }
/// <summary> /// Get or construct the node Url /// </summary> /// <param name="node">Node to process</param> /// <returns>Node Url</returns> public string GetNodeUrl(IContent node) { // Make sure we have a current Umbraco Context if (UmbracoContext.Current == null) { var dummyContext = new HttpContextWrapper(new HttpContext(new SimpleWorkerRequest("/", string.Empty, new StringWriter()))); UmbracoContext.EnsureContext( dummyContext, ApplicationContext.Current, new WebSecurity(dummyContext, ApplicationContext.Current), false); } var helper = new UmbracoHelper(UmbracoContext.Current); var entityUrl = helper.NiceUrl(node.Id); if (!string.IsNullOrEmpty(entityUrl) && entityUrl != "#") { return(entityUrl); } // Just need the Url of the parent node... entityUrl = helper.Url(node.ParentId); if (entityUrl == "#") { entityUrl = string.Empty; } if (!entityUrl.EndsWith("/")) { entityUrl += "/"; } // Then add the current node name var nodeName = node.Name; if (node.HasProperty("umbracoUrlName") && !string.IsNullOrEmpty(node.GetValue <string>("umbracoUrlName"))) { nodeName = node.GetValue <string>("umbracoUrlName"); } nodeName = umbraco.cms.helpers.url.FormatUrl(nodeName); entityUrl = string.Format("{0}{1}/", entityUrl, nodeName); return(entityUrl); }
/// <summary> /// Check permissions for selected user /// Do not include "Browse" as this is the minimum and indicates NO Permission for a page /// </summary> /// <param name="userId">Target user</param> /// <returns>User page permission set</returns> public IList <PermissionsModel> CheckUserPermissions(int userId) { var helper = new UmbracoHelper(UmbracoContext.Current); var user = _userService.GetUserById(userId); IList <PermissionsModel> permList = new List <PermissionsModel>(); // This only gets permissions that have been explicitly set, unless a page(s) Id is passed then it returns // at least the default permissions var userPermissions = _userService.GetPermissions(user); foreach (var userPerm in userPermissions) { // Assume: // if no permissions at all, then there will be only one element which will contain a "-" // If only the default permission then there will only be one element which will contain "F" (Browse Node) if (userPerm.AssignedPermissions.Count() > 1 || (userPerm.AssignedPermissions[0] != "-" && userPerm.AssignedPermissions[0] != "F")) { var contentNode = _contentService.GetById(userPerm.EntityId); if (contentNode.Trashed) { continue; } var p = new PermissionsModel { UserId = userPerm.UserId, Username = user.Username, FullName = user.Name, EmailAddress = user.Email, UserLocked = !user.IsApproved, PageId = userPerm.EntityId, PageName = contentNode.Name, PagePath = PageBreadcrumb(contentNode), PageUrl = helper.NiceUrl(contentNode.Id) }; permList.Add(p); } } return(permList); }
public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview) { if (source == null) { return(null); } var sourceString = source.ToString(); if (sourceString.DetectIsJson()) { try { var obj = JsonConvert.DeserializeObject <JArray>(sourceString); //update the internal links if we have a context if (UmbracoContext.Current != null) { var helper = new UmbracoHelper(UmbracoContext.Current); foreach (var a in obj) { var type = a.Value <string>("type"); if (type.IsNullOrWhiteSpace() == false) { if (type == "internal") { var linkId = a.Value <int>("link"); var link = helper.NiceUrl(linkId); a["link"] = link; } } } } return(obj); } catch (Exception ex) { LogHelper.Error <RelatedLinksEditorValueConvertor>("Could not parse the string " + sourceString + " to a json object", ex); } } //it's not json, just return the string return(sourceString); }
private void ExternalIndexerGatheringNodeData(object sender, IndexingNodeDataEventArgs e, UmbracoHelper helper) { if (e.IndexType == IndexTypes.Content) { try { e.Fields.Add("SearchablePath", e.Fields["path"].Replace(",", " ")); //we can then search using languge root node var fields = e.Fields; var combinedFields = new StringBuilder(); foreach (var keyValuePair in fields) { if (keyValuePair.Key != "grid") { combinedFields.AppendLine(keyValuePair.Value); } } if (e.Fields.ContainsKey("grid")) { //we have grid field we want to screen scrap IWebScraper scraper = new WebScraper(); string contentUrlWithDomain = helper.NiceUrl(e.NodeId); string scrapedGridContent = scraper.ScrapeByClass(contentUrlWithDomain, "umb-grid"); combinedFields.AppendLine(scrapedGridContent); } e.Fields.Add("contents", combinedFields.ToString()); } catch (Exception ex) { LogHelper.Error <Exception>("error munging fields for " + e.NodeId, ex); } } }
/// <summary> /// Find all pages that do not have any Web Authors assigned /// </summary> /// <returns>Content Items</returns> public IList <PermissionsModel> GetPagesWithoutAuthor() { int totalRecords; // Get the Web Author User Type var userType = _userService.GetUserTypeByAlias(_webAuthorUserType); // Get all users whose type is Web Author var users = _userService.GetAll(0, int.MaxValue, out totalRecords).Where(t => t.UserType.Id == userType.Id); // Get unique list of pages that have a Web Author IList <int> webAuthorPages = new List <int>(); foreach (var u in users) { // If user is locked / Disabled then their permissions do not apply if (!u.IsApproved) { continue; } var userPermissions = _userService.GetPermissions(u); foreach (var userPerm in userPermissions) { // Assume: // if no permissions at all, then there will be only one element which will contain a "-" // If only the default permission then there will only be one element which will contain "F" (Browse Node) if (userPerm.AssignedPermissions.Count() > 1 || (userPerm.AssignedPermissions[0] != "-" && userPerm.AssignedPermissions[0] != "F")) { if (!webAuthorPages.Contains(userPerm.EntityId)) { webAuthorPages.Add(userPerm.EntityId); } } } } // Get ALL site content var helper = new UmbracoHelper(UmbracoContext.Current); var permList = new List <PermissionsModel>(); var rootContent = _contentService.GetRootContent().OrderBy(o => o.SortOrder); foreach (var rootNode in rootContent) { // Ignore pages in the Recycle Bin if (rootNode.Trashed) { continue; } // Check if any Web Authors have permissions for this root node if (!webAuthorPages.Contains(rootNode.Id)) { var rn = new PermissionsModel { PageId = rootNode.Id, PageName = rootNode.Name, PagePath = PageBreadcrumb(rootNode), PageUrl = library.NiceUrl(rootNode.Id) }; permList.Add(rn); } // Extract all content that is NOT included in the webAuthorPages list // i.e. those pages that DO NOT have a currently enabled web author assigned var allContent = rootNode.Descendants().Where(a => !webAuthorPages.Contains(a.Id)).OrderBy(o => o.SortOrder); foreach (var contentItem in allContent) { if (contentItem.Trashed) { continue; } var p = new PermissionsModel { PageId = contentItem.Id, PageName = contentItem.Name, PagePath = PageBreadcrumb(contentItem), PageUrl = helper.NiceUrl(contentItem.Id) }; permList.Add(p); } } return(permList.OrderBy(o => o.PagePath).ToList()); }
/// <summary> /// The event that fires whenever a resource is requested /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void UmbracoApplication_PreRequestHandlerExecute(object sender, EventArgs e) { var context = ((UmbracoApplicationBase)sender).Context; // if no context, session or anonymous user return if (context == null) { return; } if (context.Session == null) { return; } if (context.Request.LogonUserIdentity == null) { return; } if (context.Items == null) { return; } var umbPageId = context.Items["pageID"]; var umbPage = context.Items["UmbPage"]; var umbracoContext = (UmbracoContext)context.Items["Umbraco.Web.UmbracoContext"]; if (umbPageId == null || umbPage == null || umbracoContext == null) { return; } // if accessing via the umbraco admin return var isUmbraco = umbPage.ToString().StartsWith("/umbraco/"); if (isUmbraco) { return; } var umbracoHelper = new UmbracoHelper(umbracoContext); if (!umbracoContext.PageId.HasValue) { return; } // First we check if this page is part of a rule var page = umbracoHelper.TypedContent(umbracoContext.PageId.Value); var path = page.Path.Split(new[] { ',' }).ToList(); // if the current page should be secured, the page path will contain the root page that was secured // this is how we know that this is a descendant of the secured page var hasRule = RulesPages.Intersect(path); if (hasRule.Any()) { LogHelper.Debug <KeepOutHandler>("Access rule was found"); var ruleIndex = RulesPages.IndexOf(hasRule.First()); // if multiple rules overlap, take the first var activeRule = Rules[ruleIndex]; // now we have found a rule we check if it applies to the current member LogHelper.Debug <KeepOutHandler>("Checking member '" + context.Request.LogonUserIdentity.Name + "' for membership"); var memberRoles = System.Web.Security.Roles.GetRolesForUser(context.Request.LogonUserIdentity.Name).ToList(); LogHelper.Debug <KeepOutHandler>("Found " + memberRoles.Count() + " roles for member"); if (!memberRoles.Any()) { return; } var appliesToUser = activeRule.MemberRoles.Intersect(memberRoles); if (appliesToUser.Any()) { LogHelper.Debug <KeepOutHandler>("Applicable group membership found, attempting redirect to no-access page"); // member is in a group that has been denied access, so redirect to the no access page defined by the rule var noAccessPage = umbracoHelper.NiceUrl(activeRule.NoAccessPage); umbracoContext.HttpContext.Response.Redirect(noAccessPage); } } }
/// <summary> /// Get a list of expiring pages, collated by User /// </summary> /// <param name="noOfDaysFrom"> /// How many days to look forward /// </param> /// <returns> /// List Users with expiring pages they are responsible for /// </returns> public IList <UserPagesModel> GetExpiringNodesByUser(int noOfDaysFrom) { // Get all content at the root var rootnodes = _contentService.GetRootContent(); // Create a list to store expiring content List <IContent> expiringNodes = new List <IContent>(); // for each content node at the root foreach (var node in rootnodes) { // if the node is expiring within the declared period, add it to the list if (node.ExpireDate > DateTime.Now && node.ExpireDate < DateTime.Now.AddDays(noOfDaysFrom)) { expiringNodes.Add(node); } // get the root nodes children that are expiring within the declared period. var descendants = node.Descendants().Where(nn => nn.ExpireDate > DateTime.Now && nn.ExpireDate < DateTime.Now.AddDays(noOfDaysFrom)).OrderBy(nn => nn.ExpireDate); foreach (var child in descendants) { // add each one to the list expiringNodes.Add(child); } } // once done, order by expire date. expiringNodes.OrderBy(nn => nn.ExpireDate); // For each page: IList <UserPagesModel> userPages = new List <UserPagesModel>(); // Create a WebStaff record. Use -1 as an Id as there won't be a valid Umbraco user with that value. var webStaff = new UserPagesModel(); var webstaffUser = new UmbracoUserModel { UserId = -1, UserName = "******", FullName = "Web Staff", EmailAddress = "*****@*****.**" }; webStaff.User = webstaffUser; userPages.Add(webStaff); var helper = new UmbracoHelper(UmbracoContext.Current); foreach (var expiringNode in expiringNodes) { // this should not happen, but just in case... if (expiringNode.ExpireDate == null) { continue; } var userPage = new UserPageModel { PageId = expiringNode.Id, PageName = expiringNode.Name, PagePath = expiringNode.Path, PageUrl = helper.NiceUrl(expiringNode.Id), ExpiryDate = (DateTime)expiringNode.ExpireDate }; // Get Web Authors with permission // if no permissions at all, then there will be only one element which will contain a "-" // If only the default permission then there will only be one element which will contain "F" (Browse Node) var perms = _contentService.GetPermissionsForEntity(expiringNode) .Where( x => x.AssignedPermissions.Count() > 1 || (x.AssignedPermissions[0] != "-" && x.AssignedPermissions[0] != "F")); var nodeAuthors = perms as IList <EntityPermission> ?? perms.ToList(); // if no Web Authors, add this page to the WebStaff list if (!nodeAuthors.Any()) { userPages.Where(p => p.User.UserId == -1).ForEach(u => u.Pages.Add(userPage)); continue; } // if all Authors of a page are disabled, add page to the webStaff list List <EntityPermission> disabledUsers = new List <EntityPermission>(); foreach (var user in nodeAuthors) { var tempUser = _userService.GetUserById(user.UserId); if (!tempUser.IsApproved) { disabledUsers.Add(user); } } if (disabledUsers.Count == nodeAuthors.Count) { userPages.Where(p => p.User.UserId == -1).ForEach(u => u.Pages.Add(userPage)); continue; } // Add the current page to each user that has edit rights foreach (var author in nodeAuthors) { var user = userPages.FirstOrDefault(f => f.User.UserId == author.UserId); // Create a User record if one does not yet exist if (user == null) { var pUser = _userService.GetUserById(author.UserId); // Check that this author is not Disabled / Locked Out // If they are, end this loop and move onto the next author if (!pUser.IsApproved) { continue; } var p = new UmbracoUserModel { UserId = author.UserId, UserName = pUser.Username, FullName = pUser.Name, EmailAddress = pUser.Email }; user = new UserPagesModel { User = p }; userPages.Add(user); } // Assign the current page (outer loop) to this author userPages.Where(p => p.User.UserId == user.User.UserId).ForEach(u => u.Pages.Add(userPage)); } } // Return a list of users to email, along with the page details return(userPages); }
/// <summary> /// Gets the NiceUrl for the content item /// </summary> /// <param name="doc"></param> /// <returns></returns> public static string NiceUrl(this IPublishedContent doc) { var umbHelper = new UmbracoHelper(UmbracoContext.Current); return umbHelper.NiceUrl(doc.Id); }
public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview) { if (source == null) { return(null); } var sourceString = source.ToString(); if (sourceString.DetectIsJson()) { try { var obj = JsonConvert.DeserializeObject <JArray>(sourceString); //update the internal links if we have a context if (UmbracoContext.Current == null) { return(obj); } var helper = new UmbracoHelper(UmbracoContext.Current); foreach (var a in obj) { var type = a.Value <string>("type"); if (type.IsNullOrWhiteSpace() == false) { if (type == "internal") { switch (propertyType.PropertyEditorAlias) { case Constants.PropertyEditors.RelatedLinksAlias: var intLinkId = a.Value <int>("link"); var intLink = helper.NiceUrl(intLinkId); a["link"] = intLink; break; case Constants.PropertyEditors.RelatedLinks2Alias: var strLinkId = a.Value <string>("link"); var udiAttempt = strLinkId.TryConvertTo <Udi>(); if (udiAttempt) { var content = helper.TypedContent(udiAttempt.Result); if (content == null) { break; } a["link"] = helper.NiceUrl(content.Id); } break; } } } } return(obj); } catch (Exception ex) { LogHelper.Error <LegacyRelatedLinksEditorValueConvertor>("Could not parse the string " + sourceString + " to a json object", ex); } } //it's not json, just return the string return(sourceString); }
public NavigationViewModel(IPublishedContent content) { this.CurrenPageUrl = HttpContext.Current.Request.Path; var languages = ApplicationContext.Current.Services.LocalizationService.GetAllLanguages(); if (languages != null && languages.Count() > 0) { if (languages.Any(x => x.CultureInfo.DisplayName.Equals(System.Threading.Thread.CurrentThread.CurrentCulture.DisplayName))) { this.CurrentLanguage = languages.FirstOrDefault(x => x.CultureInfo.DisplayName.Equals(System.Threading.Thread.CurrentThread.CurrentCulture.DisplayName)).CultureInfo; } this.Languages = new List <CultureInfo>(); foreach (var language in languages.Where(x => !x.CultureInfo.DisplayName.Equals(System.Threading.Thread.CurrentThread.CurrentCulture.DisplayName))) { this.Languages.Add(language.CultureInfo); } } if (content != null) { // Home Page this.HomePageInformation = new PageInformation(); if (!string.IsNullOrWhiteSpace(content.DocumentTypeAlias)) { HomePageInformation.Alias = content.DocumentTypeAlias; } if (content.GetProperty("homePage", true) != null) { HomePageInformation.Url = UmbracoHelper.NiceUrl(int.Parse(content.GetProperty("homePage", true).Value.ToString())); } if (content.GetPropertyValue("homeMenu") != null) { HomePageInformation.Name = content.GetPropertyValue("homeMenu").ToString(); } // Create Page this.CreateTicketPageInformation = new PageInformation(); if (content.GetProperty("createTicketPage", true) != null) { CreateTicketPageInformation.Url = UmbracoHelper.NiceUrl(int.Parse(content.GetProperty("createTicketPage", true).Value.ToString())); } if (content.GetPropertyValue("createTicket") != null) { CreateTicketPageInformation.Name = content.GetPropertyValue("createTicket").ToString(); } // My Tickets Page this.MyTicketsPageInformation = new PageInformation(); if (content.GetProperty("myTicketsPage", true) != null) { MyTicketsPageInformation.Url = UmbracoHelper.NiceUrl(int.Parse(content.GetProperty("myTicketsPage", true).Value.ToString())); } if (content.GetPropertyValue("myTickets") != null) { MyTicketsPageInformation.Name = content.GetPropertyValue("myTickets").ToString(); } // All Tickets Page this.AllTicketsPageInformation = new PageInformation(); if (content.GetProperty("allTicketsPage", true) != null) { AllTicketsPageInformation.Url = UmbracoHelper.NiceUrl(int.Parse(content.GetProperty("allTicketsPage", true).Value.ToString())); } if (content.GetPropertyValue("allTickets") != null) { AllTicketsPageInformation.Name = content.GetPropertyValue("allTickets").ToString(); } // Triage Page this.TriagePageInformation = new PageInformation(); if (content.GetProperty("triagePage", true) != null) { TriagePageInformation.Url = UmbracoHelper.NiceUrl(int.Parse(content.GetProperty("triagePage", true).Value.ToString())); } if (content.GetPropertyValue("triage") != null) { TriagePageInformation.Name = content.GetPropertyValue("triage").ToString(); } // Faq Page this.FaqPageInformation = new PageInformation(); if (content.GetProperty("faqPage", true) != null) { FaqPageInformation.Url = UmbracoHelper.NiceUrl(int.Parse(content.GetProperty("faqPage", true).Value.ToString())); } if (content.GetPropertyValue("faq") != null) { FaqPageInformation.Name = content.GetPropertyValue("faq").ToString(); } } }