Files
Umbraco-CMS/src/Umbraco.Web.BackOffice/Trees/ContentTreeController.cs
Bjarke Berg 37ed84871a Merge remote-tracking branch 'origin/v8/dev' into netcore/dev
# Conflicts:
#	build/NuSpecs/UmbracoCms.Core.nuspec
#	build/NuSpecs/UmbracoCms.Web.nuspec
#	src/SolutionInfo.cs
#	src/Umbraco.Core/Cache/CacheKeys.cs
#	src/Umbraco.Core/Composing/TypeFinder.cs
#	src/Umbraco.Core/Configuration/GlobalSettings.cs
#	src/Umbraco.Core/Configuration/GlobalSettingsExtensions.cs
#	src/Umbraco.Core/Configuration/IGlobalSettings.cs
#	src/Umbraco.Core/Configuration/UmbracoSettings/ContentElement.cs
#	src/Umbraco.Core/Configuration/UmbracoSettings/ContentSectionExtensions.cs
#	src/Umbraco.Core/Constants-AppSettings.cs
#	src/Umbraco.Core/Editors/UserEditorAuthorizationHelper.cs
#	src/Umbraco.Core/Extensions/StringExtensions.cs
#	src/Umbraco.Core/Extensions/UriExtensions.cs
#	src/Umbraco.Core/IO/IOHelper.cs
#	src/Umbraco.Core/IO/PhysicalFileSystem.cs
#	src/Umbraco.Core/Media/Exif/MathEx.cs
#	src/Umbraco.Core/Media/UploadAutoFillProperties.cs
#	src/Umbraco.Core/Models/Mapping/UserMapDefinition.cs
#	src/Umbraco.Core/Models/Membership/User.cs
#	src/Umbraco.Core/Models/UserExtensions.cs
#	src/Umbraco.Core/Packaging/PackageDefinitionXmlParser.cs
#	src/Umbraco.Core/PropertyEditors/ListViewConfiguration.cs
#	src/Umbraco.Core/PropertyEditors/ValueConverters/MediaPickerValueConverter.cs
#	src/Umbraco.Core/PropertyEditors/ValueConverters/MultiNodeTreePickerValueConverter.cs
#	src/Umbraco.Core/Routing/AliasUrlProvider.cs
#	src/Umbraco.Core/Routing/DefaultUrlProvider.cs
#	src/Umbraco.Core/Routing/UriUtility.cs
#	src/Umbraco.Core/Routing/UrlProviderExtensions.cs
#	src/Umbraco.Core/Runtime/CoreRuntime.cs
#	src/Umbraco.Core/RuntimeOptions.cs
#	src/Umbraco.Core/RuntimeState.cs
#	src/Umbraco.Core/Security/BackOfficeUserStore.cs
#	src/Umbraco.Core/Security/ContentPermissions.cs
#	src/Umbraco.Core/Sync/ApplicationUrlHelper.cs
#	src/Umbraco.Core/Trees/TreeNode.cs
#	src/Umbraco.Core/Udi.cs
#	src/Umbraco.Examine.Lucene/BackOfficeExamineSearcher.cs
#	src/Umbraco.Examine/Umbraco.Examine.csproj
#	src/Umbraco.Infrastructure/Examine/ContentValueSetValidator.cs
#	src/Umbraco.Infrastructure/Migrations/Install/DatabaseBuilder.cs
#	src/Umbraco.Infrastructure/Packaging/PackageDataInstallation.cs
#	src/Umbraco.Infrastructure/Persistence/SqlSyntax/SqlServerSyntaxProvider.cs
#	src/Umbraco.Infrastructure/Scoping/Scope.cs
#	src/Umbraco.Infrastructure/Search/ExamineComponent.cs
#	src/Umbraco.Infrastructure/Security/IdentityMapDefinition.cs
#	src/Umbraco.Infrastructure/Services/Implement/ContentService.cs
#	src/Umbraco.Infrastructure/Services/Implement/MediaService.cs
#	src/Umbraco.Infrastructure/Services/Implement/NotificationService.cs
#	src/Umbraco.Persistence.SqlCe/SqlCeSyntaxProvider.cs
#	src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/LocksTests.cs
#	src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/UserExtensionsTests.cs
#	src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Editors/UserEditorAuthorizationHelperTests.cs
#	src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Examine/UmbracoContentValueSetValidatorTests.cs
#	src/Umbraco.Tests/Configurations/UmbracoSettings/ContentElementTests.cs
#	src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.config
#	src/Umbraco.Tests/TestHelpers/SettingsForTests.cs
#	src/Umbraco.Tests/Testing/TestDatabase.cs
#	src/Umbraco.Tests/Web/Controllers/ContentControllerUnitTests.cs
#	src/Umbraco.Tests/Web/Controllers/FilterAllowedOutgoingContentAttributeTests.cs
#	src/Umbraco.Tests/Web/Controllers/MediaControllerUnitTests.cs
#	src/Umbraco.Web.BackOffice/Controllers/BackOfficeServerVariables.cs
#	src/Umbraco.Web.BackOffice/Controllers/CodeFileController.cs
#	src/Umbraco.Web.BackOffice/Controllers/ContentController.cs
#	src/Umbraco.Web.BackOffice/Controllers/EntityController.cs
#	src/Umbraco.Web.BackOffice/Controllers/MacrosController.cs
#	src/Umbraco.Web.BackOffice/Controllers/MediaController.cs
#	src/Umbraco.Web.BackOffice/Controllers/PackageInstallController.cs
#	src/Umbraco.Web.BackOffice/Controllers/TourController.cs
#	src/Umbraco.Web.BackOffice/Controllers/UserGroupEditorAuthorizationHelper.cs
#	src/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingContentAttribute.cs
#	src/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingMediaAttribute.cs
#	src/Umbraco.Web.BackOffice/Mapping/ContentMapDefinition.cs
#	src/Umbraco.Web.BackOffice/Services/IconService.cs
#	src/Umbraco.Web.BackOffice/Trees/ContentTreeController.cs
#	src/Umbraco.Web.BackOffice/Trees/ContentTreeControllerBase.cs
#	src/Umbraco.Web.BackOffice/Trees/FileSystemTreeController.cs
#	src/Umbraco.Web.BackOffice/Trees/MediaTreeController.cs
#	src/Umbraco.Web.Common/Extensions/FormCollectionExtensions.cs
#	src/Umbraco.Web.UI.Client/src/common/resources/content.resource.js
#	src/Umbraco.Web.UI.Client/src/views/content/overlays/publish.html
#	src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/media.controller.js
#	src/Umbraco.Web.UI.NetCore/umbraco/config/lang/da.xml
#	src/Umbraco.Web.UI.NetCore/umbraco/config/lang/en.xml
#	src/Umbraco.Web.UI.NetCore/umbraco/config/lang/en_us.xml
#	src/Umbraco.Web.UI/config/umbracoSettings.Release.config
#	src/Umbraco.Web/Cache/MemberCacheRefresher.cs
#	src/Umbraco.Web/Composing/ModuleInjector.cs
#	src/Umbraco.Web/Editors/BackOfficeController.cs
#	src/Umbraco.Web/Editors/Binders/ContentModelBinderHelper.cs
#	src/Umbraco.Web/Editors/ContentTypeController.cs
#	src/Umbraco.Web/Editors/Filters/ContentSaveValidationAttribute.cs
#	src/Umbraco.Web/Editors/Filters/MediaItemSaveValidationAttribute.cs
#	src/Umbraco.Web/Editors/Filters/UserGroupAuthorizationAttribute.cs
#	src/Umbraco.Web/Editors/TinyMceController.cs
#	src/Umbraco.Web/Editors/UserGroupsController.cs
#	src/Umbraco.Web/Editors/UsersController.cs
#	src/Umbraco.Web/ImageCropperTemplateExtensions.cs
#	src/Umbraco.Web/Logging/WebProfiler.cs
#	src/Umbraco.Web/Logging/WebProfilerProvider.cs
#	src/Umbraco.Web/Macros/PublishedContentHashtableConverter.cs
#	src/Umbraco.Web/Mvc/EnsurePublishedContentRequestAttribute.cs
#	src/Umbraco.Web/Mvc/JsonNetResult.cs
#	src/Umbraco.Web/Mvc/MemberAuthorizeAttribute.cs
#	src/Umbraco.Web/Mvc/RenderRouteHandler.cs
#	src/Umbraco.Web/PropertyEditors/MediaPickerPropertyEditor.cs
#	src/Umbraco.Web/PropertyEditors/MultiNodeTreePickerPropertyEditor.cs
#	src/Umbraco.Web/PublishedCache/NuCache/DataSource/DatabaseDataSource.cs
#	src/Umbraco.Web/RoutableDocumentFilter.cs
#	src/Umbraco.Web/Routing/ContentFinderByUrlAlias.cs
#	src/Umbraco.Web/Routing/NotFoundHandlerHelper.cs
#	src/Umbraco.Web/Routing/PublishedRouter.cs
#	src/Umbraco.Web/Runtime/WebInitialComposer.cs
#	src/Umbraco.Web/Scheduling/KeepAlive.cs
#	src/Umbraco.Web/Security/AppBuilderExtensions.cs
#	src/Umbraco.Web/Security/BackOfficeClaimsIdentityFactory.cs
#	src/Umbraco.Web/Security/Providers/UmbracoMembershipProvider.cs
#	src/Umbraco.Web/Trees/DictionaryTreeController.cs
#	src/Umbraco.Web/Trees/LanguageTreeController.cs
#	src/Umbraco.Web/Trees/LogViewerTreeController.cs
#	src/Umbraco.Web/Trees/PackagesTreeController.cs
#	src/Umbraco.Web/UmbracoApplication.cs
#	src/Umbraco.Web/UmbracoApplicationBase.cs
#	src/Umbraco.Web/UmbracoInjectedModule.cs
#	src/Umbraco.Web/WebApi/Filters/AdminUsersAuthorizeAttribute.cs
#	src/Umbraco.Web/WebApi/Filters/CheckIfUserTicketDataIsStaleAttribute.cs
#	src/Umbraco.Web/WebApi/Filters/EnsureUserPermissionForContentAttribute.cs
#	src/Umbraco.Web/WebApi/Filters/EnsureUserPermissionForMediaAttribute.cs
#	src/Umbraco.Web/WebApi/MemberAuthorizeAttribute.cs
2021-03-05 15:36:27 +01:00

374 lines
15 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Actions;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Mail;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.ContentEditing;
using Umbraco.Cms.Core.Models.Entities;
using Umbraco.Cms.Core.Models.Trees;
using Umbraco.Cms.Core.Security;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Trees;
using Umbraco.Cms.Infrastructure.Search;
using Umbraco.Cms.Web.Common.Attributes;
using Umbraco.Cms.Web.Common.Authorization;
using Umbraco.Extensions;
using Constants = Umbraco.Cms.Core.Constants;
namespace Umbraco.Cms.Web.BackOffice.Trees
{
[Authorize(Policy = AuthorizationPolicies.SectionAccessForContentTree)]
[Tree(Constants.Applications.Content, Constants.Trees.Content)]
[PluginController(Constants.Web.Mvc.BackOfficeTreeArea)]
[CoreTree]
[SearchableTree("searchResultFormatter", "configureContentResult", 10)]
public class ContentTreeController : ContentTreeControllerBase, ISearchableTree
{
private readonly UmbracoTreeSearcher _treeSearcher;
private readonly ActionCollection _actions;
private readonly IMenuItemCollectionFactory _menuItemCollectionFactory;
private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor;
private readonly IContentService _contentService;
private readonly IEntityService _entityService;
private readonly IPublicAccessService _publicAccessService;
private readonly IUserService _userService;
private readonly ILocalizationService _localizationService;
private readonly IEmailSender _emailSender;
private readonly AppCaches _appCaches;
public ContentTreeController(
ILocalizedTextService localizedTextService,
UmbracoApiControllerTypeCollection umbracoApiControllerTypeCollection,
IMenuItemCollectionFactory menuItemCollectionFactory,
IEntityService entityService,
IBackOfficeSecurityAccessor backofficeSecurityAccessor,
ILogger<ContentTreeController> logger,
ActionCollection actionCollection,
IUserService userService,
IDataTypeService dataTypeService,
UmbracoTreeSearcher treeSearcher,
ActionCollection actions,
IContentService contentService,
IPublicAccessService publicAccessService,
ILocalizationService localizationService,
IEventAggregator eventAggregator,
IEmailSender emailSender,
AppCaches appCaches)
: base(localizedTextService, umbracoApiControllerTypeCollection, menuItemCollectionFactory, entityService, backofficeSecurityAccessor, logger, actionCollection, userService, dataTypeService, eventAggregator, appCaches)
{
_treeSearcher = treeSearcher;
_actions = actions;
_menuItemCollectionFactory = menuItemCollectionFactory;
_backofficeSecurityAccessor = backofficeSecurityAccessor;
_contentService = contentService;
_entityService = entityService;
_publicAccessService = publicAccessService;
_userService = userService;
_localizationService = localizationService;
_emailSender = emailSender;
_appCaches = appCaches;
}
protected override int RecycleBinId => Constants.System.RecycleBinContent;
protected override bool RecycleBinSmells => _contentService.RecycleBinSmells();
private int[] _userStartNodes;
protected override int[] UserStartNodes
=> _userStartNodes ?? (_userStartNodes = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.CalculateContentStartNodeIds(_entityService, _appCaches));
/// <inheritdoc />
protected override TreeNode GetSingleTreeNode(IEntitySlim entity, string parentId, FormCollection queryStrings)
{
var culture = queryStrings?["culture"].ToString();
var allowedUserOptions = GetAllowedUserMenuItemsForNode(entity);
if (CanUserAccessNode(entity, allowedUserOptions, culture))
{
//Special check to see if it is a container, if so then we'll hide children.
var isContainer = entity.IsContainer; // && (queryStrings.Get("isDialog") != "true");
var node = CreateTreeNode(
entity,
Constants.ObjectTypes.Document,
parentId,
queryStrings,
entity.HasChildren);
// set container style if it is one
if (isContainer)
{
node.AdditionalData.Add("isContainer", true);
node.SetContainerStyle();
}
var documentEntity = (IDocumentEntitySlim)entity;
if (!documentEntity.Variations.VariesByCulture())
{
if (!documentEntity.Published)
node.SetNotPublishedStyle();
else if (documentEntity.Edited)
node.SetHasPendingVersionStyle();
}
else
{
if (!culture.IsNullOrWhiteSpace())
{
if (!documentEntity.Published || !documentEntity.PublishedCultures.Contains(culture))
node.SetNotPublishedStyle();
else if (documentEntity.EditedCultures.Contains(culture))
node.SetHasPendingVersionStyle();
}
}
node.AdditionalData.Add("variesByCulture", documentEntity.Variations.VariesByCulture());
node.AdditionalData.Add("contentType", documentEntity.ContentTypeAlias);
if (_publicAccessService.IsProtected(entity.Path))
node.SetProtectedStyle();
return node;
}
return null;
}
protected override ActionResult<MenuItemCollection> PerformGetMenuForNode(string id, FormCollection queryStrings)
{
if (id == Constants.System.RootString)
{
var menu = _menuItemCollectionFactory.Create();
// if the user's start node is not the root then the only menu item to display is refresh
if (UserStartNodes.Contains(Constants.System.Root) == false)
{
menu.Items.Add(new RefreshNode(LocalizedTextService, true));
return menu;
}
//set the default to create
menu.DefaultMenuAlias = ActionNew.ActionAlias;
// we need to get the default permissions as you can't set permissions on the very root node
var permission = _userService.GetPermissions(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, Constants.System.Root).First();
var nodeActions = _actions.FromEntityPermission(permission)
.Select(x => new MenuItem(x));
//these two are the standard items
menu.Items.Add<ActionNew>(LocalizedTextService, opensDialog: true);
menu.Items.Add<ActionSort>(LocalizedTextService, true, opensDialog: true);
//filter the standard items
FilterUserAllowedMenuItems(menu, nodeActions);
if (menu.Items.Any())
{
menu.Items.Last().SeparatorBefore = true;
}
// add default actions for *all* users
menu.Items.Add(new RefreshNode(LocalizedTextService, true));
return menu;
}
//return a normal node menu:
int iid;
if (int.TryParse(id, out iid) == false)
{
return NotFound();
}
var item = _entityService.Get(iid, UmbracoObjectTypes.Document);
if (item == null)
{
return NotFound();
}
//if the user has no path access for this node, all they can do is refresh
if (!_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.HasContentPathAccess(item, _entityService, _appCaches))
{
var menu = _menuItemCollectionFactory.Create();
menu.Items.Add(new RefreshNode(LocalizedTextService, true));
return menu;
}
var nodeMenu = GetAllNodeMenuItems(item);
//if the content node is in the recycle bin, don't have a default menu, just show the regular menu
if (item.Path.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries).Contains(RecycleBinId.ToInvariantString()))
{
nodeMenu.DefaultMenuAlias = null;
nodeMenu = GetNodeMenuItemsForDeletedContent(item);
}
else
{
//set the default to create
nodeMenu.DefaultMenuAlias = ActionNew.ActionAlias;
}
var allowedMenuItems = GetAllowedUserMenuItemsForNode(item);
FilterUserAllowedMenuItems(nodeMenu, allowedMenuItems);
return nodeMenu;
}
protected override UmbracoObjectTypes UmbracoObjectType => UmbracoObjectTypes.Document;
/// <summary>
/// Returns true or false if the current user has access to the node based on the user's allowed start node (path) access
/// </summary>
/// <param name="id"></param>
/// <param name="queryStrings"></param>
/// <returns></returns>
protected override bool HasPathAccess(string id, FormCollection queryStrings)
{
var entity = GetEntityFromId(id);
return HasPathAccess(entity, queryStrings);
}
protected override ActionResult<IEnumerable<IEntitySlim>> GetChildEntities(string id, FormCollection queryStrings)
{
var result = base.GetChildEntities(id, queryStrings);
if (!(result.Result is null))
{
return result.Result;
}
var culture = queryStrings["culture"].TryConvertTo<string>();
//if this is null we'll set it to the default.
var cultureVal = (culture.Success ? culture.Result : null) ?? _localizationService.GetDefaultLanguageIsoCode();
// set names according to variations
foreach (var entity in result.Value)
{
EnsureName(entity, cultureVal);
}
return result;
}
/// <summary>
/// Returns a collection of all menu items that can be on a content node
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
protected MenuItemCollection GetAllNodeMenuItems(IUmbracoEntity item)
{
var menu = _menuItemCollectionFactory.Create();
AddActionNode<ActionNew>(item, menu, opensDialog: true);
AddActionNode<ActionDelete>(item, menu, opensDialog: true);
AddActionNode<ActionCreateBlueprintFromContent>(item, menu, opensDialog: true);
AddActionNode<ActionMove>(item, menu, true, opensDialog: true);
AddActionNode<ActionCopy>(item, menu, opensDialog: true);
AddActionNode<ActionSort>(item, menu, true, opensDialog: true);
AddActionNode<ActionAssignDomain>(item, menu, opensDialog: true);
AddActionNode<ActionRights>(item, menu, opensDialog: true);
AddActionNode<ActionProtect>(item, menu, true, opensDialog: true);
if (_emailSender.CanSendRequiredEmail())
{
menu.Items.Add(new MenuItem("notify", LocalizedTextService)
{
Icon = "megaphone",
SeparatorBefore = true,
OpensDialog = true
});
}
if((item is DocumentEntitySlim documentEntity && documentEntity.IsContainer) == false)
{
menu.Items.Add(new RefreshNode(LocalizedTextService, true));
}
return menu;
}
/// <summary>
/// Returns a collection of all menu items that can be on a deleted (in recycle bin) content node
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
protected MenuItemCollection GetNodeMenuItemsForDeletedContent(IUmbracoEntity item)
{
var menu = _menuItemCollectionFactory.Create();
menu.Items.Add<ActionRestore>(LocalizedTextService, opensDialog: true);
menu.Items.Add<ActionMove>(LocalizedTextService, opensDialog: true);
menu.Items.Add<ActionDelete>(LocalizedTextService, opensDialog: true);
menu.Items.Add(new RefreshNode(LocalizedTextService, true));
return menu;
}
/// <summary>
/// set name according to variations
/// </summary>
/// <param name="entity"></param>
/// <param name="culture"></param>
private void EnsureName(IEntitySlim entity, string culture)
{
if (culture == null)
{
if (string.IsNullOrWhiteSpace(entity.Name))
{
entity.Name = "[[" + entity.Id + "]]";
}
return;
}
if (!(entity is IDocumentEntitySlim docEntity))
{
throw new InvalidOperationException($"Cannot render a tree node for a culture when the entity isn't {typeof(IDocumentEntitySlim)}, instead it is {entity.GetType()}");
}
// we are getting the tree for a given culture,
// for those items that DO support cultures, we need to get the proper name, IF it exists
// otherwise, invariant is fine (with brackets)
if (docEntity.Variations.VariesByCulture())
{
if (docEntity.CultureNames.TryGetValue(culture, out var name) &&
!string.IsNullOrWhiteSpace(name))
{
entity.Name = name;
}
else
{
entity.Name = "(" + entity.Name + ")";
}
}
if (string.IsNullOrWhiteSpace(entity.Name))
{
entity.Name = "[[" + entity.Id + "]]";
}
}
private void AddActionNode<TAction>(IUmbracoEntity item, MenuItemCollection menu, bool hasSeparator = false, bool opensDialog = false)
where TAction : IAction
{
var menuItem = menu.Items.Add<TAction>(LocalizedTextService, hasSeparator, opensDialog);
}
public IEnumerable<SearchResultEntity> Search(string query, int pageSize, long pageIndex, out long totalFound, string searchFrom = null)
{
return _treeSearcher.ExamineSearch(query, UmbracoEntityTypes.Document, pageSize, pageIndex, out totalFound, searchFrom);
}
}
}