Ejemplo n.º 1
1
 protected virtual void WriteChild(XmlTextWriter writer, ContentItem child)
 {
     using (ElementWriter childElement = new ElementWriter("child", writer))
     {
         childElement.WriteAttribute("id", child.ID);
     }
 }
Ejemplo n.º 2
0
        public DraggableToolbar(ContentItem item, ItemDefinition definition)
        {
            if (definition == null) throw new ArgumentNullException("definition");

            this.currentItem = item;
            this.definition = definition;
        }
Ejemplo n.º 3
0
 protected ContentContextBase (ContentItem contentItem) {
     ContentItem = contentItem;
     Id = contentItem.Id;
     ContentType = contentItem.ContentType;
     ContentItemRecord = contentItem.Record;
     ContentManager = contentItem.ContentManager;
 }
Ejemplo n.º 4
0
        public override bool IsApplicable(ContentItem contentItem)
        {
            if (!contentItem.IsPage)
                return false;

            return base.IsApplicable(contentItem);
        }
Ejemplo n.º 5
0
 public void Read(XPathNavigator navigator, ContentItem item, ReadingJournal journal)
 {
     foreach (XPathNavigator detailCollectionElement in EnumerateChildren(navigator))
     {
         ReadDetailCollection(detailCollectionElement, item, journal);
     }
 }
Ejemplo n.º 6
0
		/// <summary>Appends the creator node to the given collection.</summary>
		/// <param name="items"></param>
		/// <param name="engine"></param>
		/// <param name="parent"></param>
		/// <returns></returns>
		public static IEnumerable<ContentItem> AppendCreatorNode(this IEnumerable<ContentItem> items, IEngine engine, ContentItem parent)
		{
			if (parent.ID == 0)
				return items;

			return items.Union(new[] { new CreatorItem(engine, parent) });
		}
Ejemplo n.º 7
0
		public override void Save(ContentItem item)
		{
			using (var tx = repository.BeginTransaction())
			{
				// update updated date unless it's a version being saved
				if (!item.VersionOf.HasValue)
					item.Updated = Utility.CurrentTime();
				// empty string names not allowed, null is replaced with item id
				if (string.IsNullOrEmpty(item.Name))
					item.Name = null;

				item.AddTo(item.Parent);
				
				// make sure the ordering is the same next time these siblings are loaded
				var unsavedItems = item.Parent.EnsureChildrenSortOrder();
				foreach (var itemToSave in unsavedItems.Union(new [] { item }))
				{
					repository.SaveOrUpdate(itemToSave);
				}

				// ensure a name, fallback to id
				if (string.IsNullOrEmpty(item.Name))
				{
					item.Name = item.ID.ToString();
					repository.SaveOrUpdate(item);
				}

				tx.Commit();
			}
		}
Ejemplo n.º 8
0
		public Attachment(IAttachmentHandler handler, string url, ContentItem enclosingItem, byte[] fileContents)
		{
			_handler = handler;
			_url = url;
			_enclosingItem = enclosingItem;
			_fileContents = fileContents;
		}
Ejemplo n.º 9
0
        public bool Transform(ContentItem item)
        {
            string text = item[Name] as string;
            if(text != null)
            {
                string detailName = Name + "_Tokens";
                int i = 0;
                var p = new Parser(new TemplateAnalyzer());
                foreach (var c in p.Parse(text).Where(c => c.Command != Parser.TextCommand))
                {
                    var dc = item.GetDetailCollection(detailName, true);
                    var cd = ContentDetail.Multi(detailName, stringValue: c.Tokens.Select(t => t.Fragment).StringJoin(), integerValue: c.Tokens.First().Index);
                    cd.EnclosingItem = item;
                    cd.EnclosingCollection = dc;

                    if (dc.Details.Count > i)
                        dc.Details[i] = cd;
                    else
                        dc.Details.Add(cd);
                    i++;
                }
                if (i > 0)
                {
                    var dc = item.GetDetailCollection(detailName, true);
                    for (int j = dc.Details.Count - 1; j >= i; j--)
                    {
                        dc.Details.RemoveAt(j);
                    }
                    return true;
                }
            }
            return false;
        }
Ejemplo n.º 10
0
		public virtual ContentItem Navigate(ContentItem startingPoint, string path)
		{
			return startingPoint.GetChild(path)
				?? sources.ResolvePath(startingPoint, path).CurrentItem
				?? virtualNodes.Get(startingPoint.Path + path.TrimStart('/'))
				?? virtualNodes.Get(path);
		}
		public override bool UpdateItem(ContentItem item, Control editor)
		{
			TextBox tb = (TextBox)editor;
			string[] rows = tb.Text.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
			for (int i = item.Children.Count - 1; i >= 0; --i)
			{
				int index = Array.FindIndex(rows, delegate(string row)
													  {
														  return row == item.Children[i].Title;
													  }
					);
				if (index < 0)
					Context.Persister.Delete(item.Children[i]);
			}
			for (int i = 0; i < rows.Length; i++)
			{
				ContentItem child = FindChild(item, rows[i]);
				if (child == null)
				{
					child = new Option();
					child.Title = rows[i];
					child.AddTo(item);
				}
				child.SortOrder = i;

				editor.RegisterItemToSave(child);
			}

			return true;
		}
Ejemplo n.º 12
0
 public void Read(System.Xml.XPath.XPathNavigator navigator, ContentItem item, ReadingJournal journal)
 {
     foreach (XPathNavigator detailElement in EnumerateChildren(navigator))
     {
         ReadProperty(detailElement, item, journal);
     }
 }
Ejemplo n.º 13
0
		/// <summary>Gets the url for the navigation frame.</summary>
		/// <param name="selectedItem">The currently selected item.</param>
		/// <returns>An url.</returns>
		public virtual string GetNavigationUrl(ContentItem selectedItem)
		{
			if (selectedItem == null)
				return null;

			return Url.Parse(EditTreeUrl).AppendQuery(SelectionUtility.SelectedQueryKey, selectedItem.Path);
		}
Ejemplo n.º 14
0
		internal static void Write(HierarchyNode<ContentItem> hierarchy, ContentItem selectedItem, IContentAdapterProvider adapters, ItemFilter filter, string selectableTypes, string selectableExtensions, bool excludeRoot, string target, TextWriter writer)
		{
			N2.Web.Tree.Using(hierarchy)
				.OpenTo(selectedItem)
				.Filters(filter)
				.IdProvider(n => "u" + n.Current.ID, n => "l" + n.Current.ID)
				.LinkWriter((n, w) =>
				{
					BuildLink(adapters.ResolveAdapter<NodeAdapter>(n.Current), n.Current, n.Current.Path == selectedItem.Path, target, IsSelectable(n.Current, selectableTypes, selectableExtensions)).WriteTo(w);
					if (n.Children.Count == 0 && adapters.ResolveAdapter<NodeAdapter>(n.Current).HasChildren(n.Current, filter))
					{
						var ul = new TagBuilder("ul");
						ul.AddCssClass("ajax");
						w.Write(ul.ToString(TagRenderMode.StartTag));

						var li = new TagBuilder("li");
						li.InnerHtml = "{url:" + Url.ParseTokenized("{ManagementUrl}/Content/Navigation/LoadTree.ashx")
							.AppendQuery("target", target)
							.AppendQuery(SelectionUtility.SelectedQueryKey, HttpUtility.UrlEncode(n.Current.Path))
							.AppendQuery("selectableTypes", selectableTypes)
							.AppendQuery("selectableExtensions", selectableExtensions)
							+ "}";
						w.Write(li.ToString());

						w.Write(ul.ToString(TagRenderMode.EndTag));
					}
				})
				.ExcludeRoot(excludeRoot)
				.WriteTo(writer);
		}
Ejemplo n.º 15
0
        public PathData GetPath(ContentItem item, string remainingUrl)
        {
            int slashIndex = remainingUrl.IndexOf('/');

            string action = remainingUrl;
            string arguments = null;
            if(slashIndex > 0)
            {
                action = remainingUrl.Substring(0, slashIndex);
                arguments = remainingUrl.Substring(slashIndex + 1);
            }

            var controllerName = controllerMapper.GetControllerName(item.GetContentType());
            if (string.IsNullOrEmpty(action) || string.Equals(action, "Default.aspx", StringComparison.InvariantCultureIgnoreCase))
                action = "Index";

            foreach (string method in methods)
            {
                if (string.Equals(method, action, StringComparison.InvariantCultureIgnoreCase))
                {
                    return new PathData(item, null, action, arguments)
                    {
                        IsRewritable = false,
                        TemplateUrl = string.Format("~/{0}/{1}", controllerName, method, item.ID) // workaround for start pages
                    };
                }
            }

            return null;
        }
Ejemplo n.º 16
0
 private static bool IsAuthorized(object possiblySecurable, IPrincipal user, ContentItem item)
 {
     var securable = possiblySecurable as ISecurable;
     if (securable != null && securable.AuthorizedRoles != null && !PermissionMap.IsInRoles(user, securable.AuthorizedRoles))
         return false;
     return true;
 }
Ejemplo n.º 17
0
		public override Control AddTo(ContentItem item, string detailName, Control container)
		{
			Control displayer = (Control)Activator.CreateInstance(ControlType);
			Utility.SetProperty(displayer, ControlPropertyName, item[detailName]);
			container.Controls.Add(displayer);
			return displayer;
		}
Ejemplo n.º 18
0
 private static bool IsPermitted(ISecurityManager security, object possiblyPermittable, IPrincipal user, ContentItem item)
 {
     var permittable = possiblyPermittable as IPermittable;
     if (permittable != null && permittable.RequiredPermission > Permission.Read && !security.IsAuthorized(user, item, permittable.RequiredPermission))
         return false;
     return true;
 }
Ejemplo n.º 19
0
 protected override bool IsStartPage(ContentItem item)
 {
     foreach (Site site in Host.Sites)
         if (IsStartPage(item, site))
             return true;
     return base.IsStartPage(item);
 }
Ejemplo n.º 20
0
        private string GetClassName(ContentItem item)
        {
            var className = new StringBuilder();
	        var currentTime = N2.Utility.CurrentTime();
            if (!item.Published.HasValue || item.Published > currentTime)
                className.Append("unpublished ");
            else if (item.Published > currentTime.AddDays(-1))
                className.Append("day ");
            else if (item.Published > currentTime.AddDays(-7))
                className.Append("week ");
            else if (item.Published > currentTime.AddMonths(-1))
                className.Append("month ");

            if (item.Expires.HasValue && item.Expires <= currentTime)
                className.Append("expired ");

            if (!item.Visible)
                className.Append("invisible ");

            if (item.AlteredPermissions != Permission.None && item.AuthorizedRoles != null &&
                item.AuthorizedRoles.Count > 0)
                className.Append("locked ");

            return className.ToString();
        }
Ejemplo n.º 21
0
        public UpdateContentItemAction(IView view, IController con, ContentItem item, PropertyDescriptor property, object previousValue)
        {
            _view = view;
            _con = con;

            _state = ContentItemState.Get(item);

            var name = property.Name;
            var value = previousValue;

            if (name == "Importer")
            {
                name = "ImporterName";
                value = ((ImporterTypeDescription)value).TypeName;
            }

            if (name == "Processor")
            {
                name = "ProcessorName";
                value = ((ProcessorTypeDescription)value).TypeName;
            }

            var field = _state.GetType().GetMember(name).SingleOrDefault() as FieldInfo;
            if (field == null)
            {
                if (!_state.ProcessorParams.ContainsKey(name))
                    throw new Exception();

                _state.ProcessorParams[name] = value;
            }
            else
            {
                field.SetValue(_state, value);
            }
        }
Ejemplo n.º 22
0
        public Displayable(HtmlHelper helper, string propertyName, ContentItem currentItem)
            : base(helper, currentItem)
        {
            if (propertyName == null) throw new ArgumentNullException("propertyName");

            this.propertyName = propertyName;
        }
Ejemplo n.º 23
0
        protected override void OnInit(EventArgs e)
        {
            selectedItem = Selection.ParseSelectionFromRequest();

            if (selectedItem != null)
            {
                itemsToDelete.CurrentItem = selectedItem;
                itemsToDelete.DataBind();

                ParameterCollection query = Parameter.Equal("State", ContentState.Deleted);
                if (selectedItem.ID != 0)
                    query &= (Parameter.Like(LinkTracker.Tracker.LinkDetailName, selectedItem.Url).Detail() | Parameter.Equal(null, selectedItem).Detail());
                else
                    query &= Parameter.Like(LinkTracker.Tracker.LinkDetailName, selectedItem.Url).Detail();
                var count = Engine.Persister.Repository.Count(query);

                if (count > 0)
                {
                    chkAllow.Text += " (" + count + ")";
                    rptReferencing.DataSource = Engine.Persister.Repository.Find(query.Take(10)).Where(Content.Is.Distinct());
                    rptReferencing.DataBind();
                    hlReferencingItems.Visible = (count > 10);
                }
                else
                    referencingItems.Visible = false;

                this.hlReferencingItems.NavigateUrl = "Dependencies.aspx?" + SelectionUtility.SelectedQueryKey + "=" + selectedItem.Path + "&returnUrl=" + Server.HtmlEncode(Request.RawUrl);
            }

            base.OnInit(e);
        }
Ejemplo n.º 24
0
 public ViewPageResult(ContentItem thePage, IControllerMapper controllerMapper, IWebContext webContext, IActionInvoker actionInvoker)
 {
     _thePage = thePage;
     _controllerMapper = controllerMapper;
     _webContext = webContext;
     _actionInvoker = actionInvoker;
 }
Ejemplo n.º 25
0
 private static void CopyAutoImplementedProperties(ContentItem source, ContentItem destination)
 {
     foreach (var property in source.GetContentType().GetProperties().Where(pi => pi.IsInterceptable()))
     {
         destination[property.Name] = TryClone(source[property.Name]);
     }
 }
Ejemplo n.º 26
0
 public override bool Match(ContentItem item)
 {
     foreach (ItemFilter filter in filters)
         if (!filter.Match(item))
             return false;
     return true;
 }
Ejemplo n.º 27
0
        /// <summary>Checks whether an item  may have versions.</summary>
        /// <param name="item">The item to check.</param>
        /// <returns>True if the item is allowed to have versions.</returns>
        public bool IsVersionable(ContentItem item)
        {
            var versionables = (VersionableAttribute[])item.GetContentType().GetCustomAttributes(typeof(VersionableAttribute), true);
            bool isVersionable = versionables.Length == 0 || versionables[0].Versionable == N2.Definitions.AllowVersions.Yes;

            return isVersionable;
        }
Ejemplo n.º 28
0
		/// <summary>Creates a navigation using unordered list elements.</summary>
		public static N2.Web.Tree Tree(this HtmlHelper html,
			ContentItem startsFrom = null,
			ContentItem current = null,
			int takeLevels = 2,
			bool parallelRoot = true,
			bool appendCreatorNode = false,
			ItemFilter filter = null,
			object htmlAttributes = null)
		{
			if (startsFrom == null) startsFrom = html.StartPage();
			if (current == null) current = html.CurrentPage();
			if (filter == null) filter = new NavigationFilter(html.ViewContext.HttpContext.User, html.ContentEngine().SecurityManager);

			var builder = parallelRoot
				? (HierarchyBuilder)new ParallelRootHierarchyBuilder(startsFrom, takeLevels)
				: (HierarchyBuilder)new TreeHierarchyBuilder(startsFrom, takeLevels);

			if (builder == null)
				throw new ArgumentException("builder == null");

			if (appendCreatorNode && ControlPanelExtensions.GetControlPanelState(html).IsFlagSet(ControlPanelState.DragDrop))
				builder.GetChildren = (i) => i == null ? null : i.Children.FindNavigatablePages().Where(filter).AppendCreatorNode(html.ContentEngine(), i);
			else
				builder.GetChildren = (i) => i == null ? null : i.Children.FindNavigatablePages().Where(filter);

			var tree = N2.Web.Tree.Using(builder);
			if (htmlAttributes != null)
				tree.Tag(ApplyToRootUl(htmlAttributes));

			ClassifyAnchors(startsFrom, current, parallelRoot, tree);

			return tree;
		}
Ejemplo n.º 29
0
		/// <summary>Reorders children according to OrderBy.</summary>
		/// <param name="item">The item whose children to re-order.</param>
		/// <returns>Items that were changed in the process of ordering. These items needs to be saved for the order to be persisted.</returns>
		public virtual IEnumerable<ContentItem> ReorderChildren(ContentItem item)
		{
			switch (OrderBy)
			{
				case SortBy.Updated:
					return ReorderBy(item, "Updated");
				case SortBy.UpdatedDescending:
					return ReorderBy(item, "Updated DESC");
				case SortBy.CurrentOrder:
					return Utility.UpdateSortOrder(item.Children);
				case SortBy.Expression:
					return ReorderBy(item, SortExpression);
				case SortBy.Published:
					return ReorderBy(item, "Published");
				case SortBy.PublishedDescending:
					return ReorderBy(item, "Published DESC");
				case SortBy.Title:
					return ReorderBy(item, "Title");
				case SortBy.Unordered:
				case SortBy.Append:
					return Enumerable.Empty<ContentItem>();
				default:
					throw new ArgumentException("Unknown sort order: " + OrderBy);
			}
		}
Ejemplo n.º 30
0
        public override void SetUp()
        {
            base.SetUp();

            root = CreateOneItem<RootNode>(1, "root", null);
            start = CreateOneItem<RootNode>(2, "start", root);
            host = new Host(new ThreadContext(), root.ID, start.ID);

            fs = new FakeMappedFileSystem();
            fs.BasePath = AppDomain.CurrentDomain.BaseDirectory + @"\FileSystem\";

            vnf = new VirtualNodeFactory();
            config = new EditSection();

            injector = new FakeDependencyInjector();
            injector.injectors.Add(new EntityDependencySetter<IFileSystem>(fs));
            injector.injectors.Add(new EntityDependencySetter<IDependencyInjector>(injector));
            var sizeCache = new ImageSizeCache(new ConfigurationManagerWrapper { Sections = new ConfigurationManagerWrapper.ContentSectionTable(null, null, null, config) });
            injector.injectors.Add(new EntityDependencySetter<ImageSizeCache>(sizeCache));
            //nodeProvider = new FolderNodeProvider(fs, persister, injector);
            //initializer = new VirtualFolderInitializer(host, persister, fs, vnf, new Plugin.ConnectionMonitor().SetConnected(SystemStatusLevel.UpAndRunning), config, new ImageSizeCache(new ConfigurationManagerWrapper { Sections = new ConfigurationManagerWrapper.ContentSectionTable(null, null, null, config) }), nodeProvider);
            //nodeProvider = new FolderNodeProvider(fs, persister, injector);
            //nodeProvider = new FolderNodeProvider(fs, persister, injector);
            nodeProvider = new FolderNodeProvider(fs, persister.Repository, injector);
            initializer = new VirtualFolderInitializer(host, persister, fs, vnf, monitor = new Plugin.ConnectionMonitor().SetConnected(SystemStatusLevel.UpAndRunning), new UploadFolderSource(host, config), nodeProvider);
        }
Ejemplo n.º 31
0
        /// <summary>Finds the path associated with an url.</summary>
        /// <param name="url">The url to the template to locate.</param>
        /// <param name="startNode">The node to start finding path from if none supplied will start from StartNode</param>
        /// <param name="remainingPath">The remaining path to search</param>
        /// <returns>A PathData object. If no template was found the object will have empty properties.</returns>
        public PathData FindPath(Url url, ContentItem startNode = null, string remainingPath = null)
        {
            if (url == null)
            {
                return(PathData.Empty);
            }
            if (!IsOnline)
            {
                return(PathData.Empty);
            }

            Url         requestedUrl = url;
            ContentItem item         = TryLoadingFromQueryString(requestedUrl, PathData.ItemQueryKey);
            ContentItem page         = TryLoadingFromQueryString(requestedUrl, PathData.PageQueryKey);

            if (page != null)
            {
                var directPath = page.FindPath(requestedUrl["action"] ?? PathData.DefaultAction)
                                 .SetArguments(requestedUrl["arguments"])
                                 .UpdateParameters(requestedUrl.GetQueries());

                var directData = UseItemIfAvailable(item, directPath);
                // check whether to rewrite requests with page in query string since this might be already rewritten
                directData.IsRewritable &= !string.Equals(url.ApplicationRelativePath, directData.TemplateUrl, StringComparison.InvariantCultureIgnoreCase);
                return(directData);
            }

            ContentItem startPage = startNode ?? GetStartPage(requestedUrl);

            if (startPage == null)
            {
                return(PathData.Empty);
            }

            string   path = remainingPath ?? Url.ToRelative(requestedUrl.Path).TrimStart('~');
            PathData data = startPage.FindPath(path).UpdateParameters(requestedUrl.GetQueries());

            if (data.IsEmpty())
            {
                if (!string.IsNullOrEmpty(DefaultDocument) && path.EndsWith(DefaultDocument, StringComparison.OrdinalIgnoreCase))
                {
                    // Try to find path without default document.
                    data = StartPage
                           .FindPath(StripDefaultDocument(path))
                           .UpdateParameters(requestedUrl.GetQueries());
                }

                if (data.IsEmpty())
                {
                    // Allow user code to set path through event
                    if (PageNotFound != null)
                    {
                        PageNotFoundEventArgs args = new PageNotFoundEventArgs(requestedUrl);
                        args.AffectedPath = data;
                        PageNotFound(this, args);
                        data = args.AffectedPath;
                    }
                }
            }

            data.Ignore = !IgnoreExisting(webContext.HttpContext.Request.PhysicalPath);
            data        = UseItemIfAvailable(item, data);
            return(data);
        }
Ejemplo n.º 32
0
 /// <summary>Creates a list of the parents of the initial item.</summary>
 /// <param name="initialItem">The page whose parents will be enumerated. The page itself will not appear in the enumeration.</param>
 /// <returns>A list of the parents of the initial page.</returns>
 public static IList <ContentItem> ListParents(ContentItem initialItem)
 {
     return(new List <ContentItem>(EnumerateParents(initialItem)));
 }
Ejemplo n.º 33
0
 /// <summary>The from result file.</summary>
 /// <param name="context">The context.</param>
 /// <param name="cacheCategory">The cache category.</param>
 /// <param name="endResult">The end result.</param>
 /// <param name="fileCategory">The file category.</param>
 /// <param name="contentItem">The result file.</param>
 /// <returns>The <see cref="CacheResult"/>.</returns>
 public static CacheResult FromContentFile(IWebGreaseContext context, string cacheCategory, bool endResult, string fileCategory, ContentItem contentItem)
 {
     return(new CacheResult
     {
         EndResult = endResult,
         FileCategory = fileCategory,
         CachedFilePath = context.Cache.StoreInCache(cacheCategory, contentItem),
         ContentHash = contentItem.GetContentHash(context),
         RelativeContentPath = contentItem.RelativeContentPath,
         RelativeHashedContentPath = contentItem.RelativeHashedContentPath,
     });
 }
Ejemplo n.º 34
0
 public CloneContentContext(ContentItem contentItem, ContentItem cloneContentItem)
     : base(contentItem)
 {
     CloneContentItem = cloneContentItem;
 }
Ejemplo n.º 35
0
 public UpdateItemCommand(ContentItem item)
 {
     Item = item;
 }
Ejemplo n.º 36
0
 /// <summary>
 /// Gets the item at of the specified type.
 /// </summary>
 /// <returns>An ancestor at the specified level.</returns>
 public static ContentItem ClosestOf <T>(ContentItem item) where T : class
 {
     return(Closest <T>(item) as ContentItem);
 }
Ejemplo n.º 37
0
 /// <summary>Enumerates itself, child items and their children, and so on.</summary>
 /// <param name="item">The parent item whose child items to enumerate. The item itself is not returned.</param>
 /// <param name="includeSelf">Enumerate the item itself and it's descendants.</param>
 /// <returns>An enumeration of all children of an item.</returns>
 public static IEnumerable <ContentItem> EnumerateChildren(ContentItem item, bool includeSelf)
 {
     return(EnumerateChildren(item, includeSelf, true));
 }
Ejemplo n.º 38
0
 /// <summary>Enumerates child items and their children, and so on.</summary>
 /// <param name="item">The parent item whose child items to enumerate. The item itself is not returned.</param>
 /// <returns>An enumeration of all children of an item.</returns>
 public static IEnumerable <ContentItem> EnumerateChildren(ContentItem item)
 {
     return(EnumerateChildren(item, false, true));
 }
Ejemplo n.º 39
0
        /// <summary>Enumerates the trail of items from the last ancestor to the deepest child.</summary>
        /// <param name="deepestChild">The page whose parents will be enumerated. The page itself will appear in the enumeration if includeSelf is applied.</param>
        /// <param name="lastAncestor">The first page of the enumeration.</param>
        /// <param name="includeDeepestChild">Include the deepest child in the enumeration.</param>
        /// <returns>An enumeration of the from the ancestor uptil the deepest child.</returns>
        public static IEnumerable <ContentItem> EnumerateBetween(ContentItem lastAncestor, ContentItem deepestChild, bool includeDeepestChild)
        {
            IList <ContentItem> items = ListParents(deepestChild, lastAncestor, includeDeepestChild);

            for (int i = items.Count - 1; i >= 0; --i)
            {
                yield return(items[i]);
            }
        }
Ejemplo n.º 40
0
 /// <summary>Creates a list of the parents of the initial item.</summary>
 /// <param name="initialItem">The page whose parents will be enumerated. The page itself will not appear in the enumeration.</param>
 /// <param name="lastAncestor">The last page of the enumeration. The enumeration will contain this page.</param>
 /// <returns>A list of the parents of the initial page. If the last page isn't a parent of the inital page all pages until there are no more parents are returned.</returns>
 public static IList <ContentItem> ListParents(ContentItem initialItem, ContentItem lastAncestor)
 {
     return(new List <ContentItem>(EnumerateParents(initialItem, lastAncestor)));
 }
Ejemplo n.º 41
0
 /// <summary>Enumerates parents of the initial item.</summary>
 /// <param name="initialItem">The page whose parents will be enumerated. The page itself will not appear in the enumeration.</param>
 /// <param name="lastAncestor">The last page of the enumeration. The enumeration will contain this page.</param>
 /// <returns>An enumeration of the parents of the initial page. If the last page isn't a parent of the inital page all pages until there are no more parents are returned.</returns>
 public static IEnumerable <ContentItem> EnumerateParents(ContentItem initialItem, ContentItem lastAncestor)
 {
     return(EnumerateParents(initialItem, lastAncestor, false));
 }
Ejemplo n.º 42
0
        /// <summary>Enumerates parents of the initial item.</summary>
        /// <param name="initialItem">The page whose parents will be enumerated. The page itself will appear in the enumeration if includeSelf is applied.</param>
        /// <param name="lastAncestor">The last page of the enumeration. The enumeration will contain this page.</param>
        /// <param name="includeSelf">Include the initial item in the enumeration.</param>
        /// <returns>An enumeration of the parents of the initial page. If the last page isn't a parent of the inital page all pages until there are no more parents are returned.</returns>
        public static IEnumerable <ContentItem> EnumerateParents(ContentItem initialItem, ContentItem lastAncestor, bool includeSelf, bool useMasterVersion = true)
        {
            if (initialItem == null)
            {
                yield break;
            }
            if (useMasterVersion && initialItem.VersionOf.HasValue)
            {
                initialItem = initialItem.VersionOf;
            }

            ContentItem item;

            if (includeSelf)
            {
                item = initialItem;
            }
            else if (initialItem != lastAncestor)
            {
                item = initialItem.Parent;
            }
            else
            {
                yield break;
            }

            while (item != null)
            {
                yield return(item);

                if (item == lastAncestor)
                {
                    break;
                }
                item = item.Parent;
            }
        }
 public UpdateContentContext(ContentItem contentItem) : base(contentItem)
 {
     UpdatingItemVersionRecord = contentItem.VersionRecord;
 }
Ejemplo n.º 44
0
 /// <summary>Enumerates parents of the initial item.</summary>
 /// <param name="initialItem">The page whose parents will be enumerated. The page itself will not appear in the enumeration.</param>
 /// <returns>An enumeration of the parents of the initial page.</returns>
 public static IEnumerable <ContentItem> EnumerateParents(ContentItem initialItem)
 {
     return(EnumerateParents(initialItem, null));
 }
Ejemplo n.º 45
0
 /// <inheritdoc />
 public override void OnItemReimported(ContentItem item)
 {
     // Invalidate data
     _isWaitingForLoad = true;
 }
Ejemplo n.º 46
0
 /// <summary>Checks if an item is startpage or root page</summary>
 /// <param name="item">The item to compare</param>
 /// <returns>True if the item is a startpage or a rootpage</returns>
 public virtual bool IsRootOrStartPage(ContentItem item)
 {
     return(item.ID == host.CurrentSite.RootItemID || host.IsStartPage(item));
 }
Ejemplo n.º 47
0
 public Task UpdateContentItem(ContentItem contentItem)
 {
     return(_contentItemCommands.UpdateAsync(contentItem.AppId, contentItem.Id, contentItem));
 }
Ejemplo n.º 48
0
 /// <summary>Finds the path associated with an url.</summary>
 /// <param name="url">The url to the template to locate.</param>
 /// <param name="startNode">The node to start finding path from if none supplied will start from StartNode</param>
 /// <param name="remainingPath">The remaining path to search</param>
 /// <returns>A PathData object. If no template was found the object will have empty properties.</returns>
 public PathData ResolvePath(Url url, ContentItem startNode = null, string remainingPath = null)
 {
     return(FindPath(url, startNode, remainingPath));
 }
Ejemplo n.º 49
0
 public RemoveContentContext(ContentItem contentItem)
     : base(contentItem)
 {
 }
Ejemplo n.º 50
0
        /// <summary>Calculates an item url by walking it's parent path.</summary>
        /// <param name="item">The item whose url to compute.</param>
        /// <returns>A friendly url to the supplied item.</returns>
        public virtual Url BuildUrl(ContentItem item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            if (item.VersionOf.HasValue)
            {
                ContentItem version = item.VersionOf;
                if (version != null)
                {
                    return(BuildUrl(version)
                           .SetQueryParameter(PathData.VersionIndexQueryKey, item.VersionIndex));
                }
            }
            else if (item.ID == 0)
            {
                var page = Find.ClosestPage(item);
                if (page != null && page != item)
                {
                    return(BuildUrl(page)
                           .SetQueryParameter(PathData.VersionIndexQueryKey, page.VersionIndex)
                           .SetQueryParameter("versionKey", item.GetVersionKey()));
                }
            }

            var current = Find.ClosestPage(item);

            // no page found, throw
            if (current == null)
            {
                throw new N2Exception("Cannot build url to data item '{0}' with no containing page item.", item);
            }

            Url url = BuildPageUrl(current, ref current);

            if (current == null)
            {
                // no start page found, use rewritten url
                return(item.FindPath(PathData.DefaultAction).GetRewrittenUrl());
            }

            if (!item.IsPage)
            {
                // the item was not a page, add this information as a query string
                url = url.AppendQuery(PathData.ItemQueryKey, item.ID);
            }

            var absoluteUrl = Url.ToAbsolute("~" + url);

            if (BuiltUrl != null)
            {
                var args = new UrlEventArgs(item)
                {
                    Url = absoluteUrl
                };
                BuiltUrl(this, args);
                return(args.Url);
            }
            else
            {
                return(absoluteUrl);
            }
        }
Ejemplo n.º 51
0
 /// <summary>Gets the path to the given item's template. This is a way to override the default template provided by the content item.</summary>
 /// <param name="item">The item whose path is requested.</param>
 /// <returns>The virtual path of the template or null if the item is not supposed to be added.</returns>
 protected virtual string GetTemplateUrl(ContentItem item)
 {
     return(item.FindPath(PathData.DefaultAction).TemplateUrl);
 }
Ejemplo n.º 52
0
 public ItemEditor(ContentItem item)
     : this()
 {
     CurrentItem = item;
 }
Ejemplo n.º 53
0
 /// <summary>Retrieves allowed item definitions.</summary>
 /// <param name="parentItem">The parent item.</param>
 /// <param name="user">The user to restrict access for.</param>
 /// <returns>Item definitions allowed by zone, parent restrictions and security.</returns>
 public virtual IEnumerable <ItemDefinition> GetAllowedDefinitions(ContentItem parentItem, IPrincipal user)
 {
     return(Definitions.GetAllowedChildren(parentItem)
            .Where(d => d.Enabled && d.AllowedIn != Integrity.AllowedZones.None && d.Enabled)
            .WhereAuthorized(Security, user, parentItem));
 }
Ejemplo n.º 54
0
 public virtual IEnumerable <TemplateDefinition> GetTemplates(ContentItem item, ItemDefinition definition)
 {
     return(TemplateAggregator.GetTemplates(definition.ItemType));
 }
Ejemplo n.º 55
0
 public virtual ItemList GetItemsInZone(ContentItem parentItem, string zoneName)
 {
     return(new ItemList(GetParts(parentItem, zoneName, Interfaces.Viewing)));
 }
Ejemplo n.º 56
0
        /// <summary>Adds a content item part to a containing control hierarchy (typically a zone control). Override this method to adapt how a parent gets it's children added.</summary>
        /// <param name="item">The item to add a part.</param>
        /// <param name="container">The container control to host the part user interface.</param>
        public virtual Control AddChildPart(ContentItem item, Control container)
        {
            var adapter = Adapters.ResolveAdapter <PartsAdapter>(item);

            return(adapter.AddTo(item, container));
        }
 private IActiveContent Active(ContentItem item)
 {
     return((IActiveContent)item);
 }
Ejemplo n.º 58
0
 /// <summary>Retrieves allowed item definitions.</summary>
 /// <param name="parentItem">The parent item.</param>
 /// <param name="zoneName">The zone where children would be placed.</param>
 /// <param name="user">The user to restrict access for.</param>
 /// <returns>Item definitions allowed by zone, parent restrictions and security.</returns>
 public virtual IEnumerable <ItemDefinition> GetAllowedDefinitions(ContentItem parentItem, string zoneName, IPrincipal user)
 {
     return(Definitions.GetAllowedChildren(parentItem, zoneName)
            .WhereAuthorized(Security, user, parentItem));
 }
 public override ContentItem Copy(ContentItem source, ContentItem destination)
 {
     return(Active(source).CopyTo(destination));
 }
Ejemplo n.º 60
0
        public override IDisplayResult Display(ContentItem contentItem, IUpdateModel updater)
        {
            // We add custom alternates. This could be done generically to all shapes coming from ContentDisplayDriver but right now it's
            // only necessary on this shape. Otherwise c.f. ContentPartDisplayDriver

            var context = _httpContextAccessor.HttpContext;
            var results = new List <IDisplayResult>();
            var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(contentItem.ContentType);
            var contentsMetadataShape = Shape("ContentsMetadata",
                                              new ContentItemViewModel(contentItem))
                                        .Location("Detail", "Content:before");

            if (contentTypeDefinition != null)
            {
                contentsMetadataShape.Displaying(ctx =>
                {
                    var stereotype = "";
                    var settings   = contentTypeDefinition?.GetSettings <ContentTypeSettings>();
                    if (settings != null)
                    {
                        stereotype = settings.Stereotype;
                    }

                    if (!String.IsNullOrEmpty(stereotype) && !String.Equals("Content", stereotype, StringComparison.OrdinalIgnoreCase))
                    {
                        ctx.Shape.Metadata.Alternates.Add($"{stereotype}__ContentsMetadata");
                    }

                    var displayType = ctx.Shape.Metadata.DisplayType;

                    if (!String.IsNullOrEmpty(displayType) && displayType != "Detail")
                    {
                        ctx.Shape.Metadata.Alternates.Add($"ContentsMetadata_{ctx.Shape.Metadata.DisplayType}");

                        if (!String.IsNullOrEmpty(stereotype) && !String.Equals("Content", stereotype, StringComparison.OrdinalIgnoreCase))
                        {
                            ctx.Shape.Metadata.Alternates.Add($"{stereotype}_{displayType}__ContentsMetadata");
                        }
                    }
                });

                results.Add(contentsMetadataShape);
                results.Add(Shape("ContentsButtonEdit_SummaryAdmin", new ContentItemViewModel(contentItem)).Location("SummaryAdmin", "Actions:10"));
                results.Add(Shape("ContentsButtonActions_SummaryAdmin", new ContentItemViewModel(contentItem)).Location("SummaryAdmin", "ActionsMenu:10")
                            .RenderWhen(async() =>
                {
                    var hasPublishPermission = await _authorizationService.AuthorizeAsync(context.User, CommonPermissions.PublishContent, contentItem);
                    var hasDeletePermission  = await _authorizationService.AuthorizeAsync(context.User, CommonPermissions.DeleteContent, contentItem);
                    var hasPreviewPermission = await _authorizationService.AuthorizeAsync(context.User, CommonPermissions.PreviewContent, contentItem);
                    var hasClonePermission   = await _authorizationService.AuthorizeAsync(context.User, CommonPermissions.CloneContent, contentItem);

                    if (hasPublishPermission || hasDeletePermission || hasPreviewPermission || hasClonePermission)
                    {
                        return(true);
                    }

                    return(false);
                })
                            );
            }

            results.Add(Shape("ContentsTags_SummaryAdmin", new ContentItemViewModel(contentItem)).Location("SummaryAdmin", "Tags:10"));
            results.Add(Shape("ContentsMeta_SummaryAdmin", new ContentItemViewModel(contentItem)).Location("SummaryAdmin", "Meta:20"));

            return(Combine(results.ToArray()));
        }