-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
ContentController.cs
2705 lines (2380 loc) · 128 KB
/
ContentController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using System.Web.Security;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Services;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.Models.Mapping;
using Umbraco.Web.Mvc;
using Umbraco.Web.WebApi;
using Umbraco.Web.WebApi.Filters;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Events;
using Umbraco.Core.Models.ContentEditing;
using Umbraco.Core.Models.Validation;
using Umbraco.Web.Composing;
using Constants = Umbraco.Core.Constants;
using Umbraco.Core.PropertyEditors;
using Umbraco.Web.Actions;
using Umbraco.Web.ContentApps;
using Umbraco.Web.Editors.Binders;
using Umbraco.Web.Editors.Filters;
using Umbraco.Core.Models.Entities;
using Umbraco.Core.Persistence;
using Umbraco.Core.Security;
using Umbraco.Web.Routing;
using Umbraco.Core.Mapping;
using Umbraco.Core.Scoping;
namespace Umbraco.Web.Editors
{
/// <summary>
/// The API controller used for editing content
/// </summary>
/// <remarks>
/// This controller is decorated with the UmbracoApplicationAuthorizeAttribute which means that any user requesting
/// access to ALL of the methods on this controller will need access to the content application.
/// </remarks>
[PluginController("UmbracoApi")]
[UmbracoApplicationAuthorize(Constants.Applications.Content)]
[ContentControllerConfiguration]
public class ContentController : ContentControllerBase
{
private readonly PropertyEditorCollection _propertyEditors;
private readonly Lazy<IDictionary<string, ILanguage>> _allLangs;
private readonly IScopeProvider _scopeProvider;
public object Domains { get; private set; }
public ContentController(PropertyEditorCollection propertyEditors, IGlobalSettings globalSettings,
IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services,
AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoHelper umbracoHelper,
IScopeProvider scopeProvider)
: base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper)
{
_propertyEditors = propertyEditors ?? throw new ArgumentNullException(nameof(propertyEditors));
_allLangs = new Lazy<IDictionary<string, ILanguage>>(() => Services.LocalizationService.GetAllLanguages().ToDictionary(x => x.IsoCode, x => x, StringComparer.InvariantCultureIgnoreCase));
_scopeProvider = scopeProvider;
}
/// <summary>
/// Configures this controller with a custom action selector
/// </summary>
private class ContentControllerConfigurationAttribute : Attribute, IControllerConfiguration
{
public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
{
controllerSettings.Services.Replace(typeof(IHttpActionSelector), new ParameterSwapControllerActionSelector(
new ParameterSwapControllerActionSelector.ParameterSwapInfo("GetNiceUrl", "id", typeof(int), typeof(Guid), typeof(Udi)),
new ParameterSwapControllerActionSelector.ParameterSwapInfo("GetById", "id", typeof(int), typeof(Guid), typeof(Udi))
));
}
}
/// <summary>
/// Returns true if any content types have culture variation enabled
/// </summary>
/// <returns></returns>
[HttpGet]
[WebApi.UmbracoAuthorize, OverrideAuthorization]
public bool AllowsCultureVariation()
{
var contentTypes = Services.ContentTypeService.GetAll();
return contentTypes.Any(contentType => contentType.VariesByCulture());
}
/// <summary>
/// Return content for the specified ids
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
[FilterAllowedOutgoingContent(typeof(IEnumerable<ContentItemDisplay>))]
public IEnumerable<ContentItemDisplay> GetByIds([FromUri] int[] ids)
{
var foundContent = Services.ContentService.GetByIds(ids);
return foundContent.Select(MapToDisplay);
}
/// <summary>
/// Updates the permissions for a content item for a particular user group
/// </summary>
/// <param name="saveModel"></param>
/// <returns></returns>
/// <remarks>
/// Permission check is done for letter 'R' which is for <see cref="ActionRights"/> which the user must have access to update
/// </remarks>
[EnsureUserPermissionForContent("saveModel.ContentId", 'R')]
public IEnumerable<AssignedUserGroupPermissions> PostSaveUserGroupPermissions(UserGroupPermissionsSave saveModel)
{
if (saveModel.ContentId <= 0) throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
// TODO: Should non-admins be allowed to set granular permissions?
var content = Services.ContentService.GetById(saveModel.ContentId);
if (content == null) throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
//current permissions explicitly assigned to this content item
var contentPermissions = Services.ContentService.GetPermissions(content)
.ToDictionary(x => x.UserGroupId, x => x);
var allUserGroups = Services.UserService.GetAllUserGroups().ToArray();
//loop through each user group
foreach (var userGroup in allUserGroups)
{
//check if there's a permission set posted up for this user group
IEnumerable<string> groupPermissions;
if (saveModel.AssignedPermissions.TryGetValue(userGroup.Id, out groupPermissions))
{
//create a string collection of the assigned letters
var groupPermissionCodes = groupPermissions.ToArray();
//check if there are no permissions assigned for this group save model, if that is the case we want to reset the permissions
//for this group/node which will go back to the defaults
if (groupPermissionCodes.Length == 0)
{
Services.UserService.RemoveUserGroupPermissions(userGroup.Id, content.Id);
}
//check if they are the defaults, if so we should just remove them if they exist since it's more overhead having them stored
else if (userGroup.Permissions.UnsortedSequenceEqual(groupPermissionCodes))
{
//only remove them if they are actually currently assigned
if (contentPermissions.ContainsKey(userGroup.Id))
{
//remove these permissions from this node for this group since the ones being assigned are the same as the defaults
Services.UserService.RemoveUserGroupPermissions(userGroup.Id, content.Id);
}
}
//if they are different we need to update, otherwise there's nothing to update
else if (contentPermissions.ContainsKey(userGroup.Id) == false || contentPermissions[userGroup.Id].AssignedPermissions.UnsortedSequenceEqual(groupPermissionCodes) == false)
{
Services.UserService.ReplaceUserGroupPermissions(userGroup.Id, groupPermissionCodes.Select(x => x[0]), content.Id);
}
}
}
return GetDetailedPermissions(content, allUserGroups);
}
/// <summary>
/// Returns the user group permissions for user groups assigned to this node
/// </summary>
/// <param name="contentId"></param>
/// <returns></returns>
/// <remarks>
/// Permission check is done for letter 'R' which is for <see cref="ActionRights"/> which the user must have access to view
/// </remarks>
[EnsureUserPermissionForContent("contentId", 'R')]
public IEnumerable<AssignedUserGroupPermissions> GetDetailedPermissions(int contentId)
{
if (contentId <= 0) throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
var content = Services.ContentService.GetById(contentId);
if (content == null) throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
// TODO: Should non-admins be able to see detailed permissions?
var allUserGroups = Services.UserService.GetAllUserGroups();
return GetDetailedPermissions(content, allUserGroups);
}
private IEnumerable<AssignedUserGroupPermissions> GetDetailedPermissions(IContent content, IEnumerable<IUserGroup> allUserGroups)
{
//get all user groups and map their default permissions to the AssignedUserGroupPermissions model.
//we do this because not all groups will have true assigned permissions for this node so if they don't have assigned permissions, we need to show the defaults.
var defaultPermissionsByGroup = Mapper.MapEnumerable<IUserGroup, AssignedUserGroupPermissions>(allUserGroups);
var defaultPermissionsAsDictionary = defaultPermissionsByGroup
.ToDictionary(x => Convert.ToInt32(x.Id), x => x);
//get the actual assigned permissions
var assignedPermissionsByGroup = Services.ContentService.GetPermissions(content).ToArray();
//iterate over assigned and update the defaults with the real values
foreach (var assignedGroupPermission in assignedPermissionsByGroup)
{
var defaultUserGroupPermissions = defaultPermissionsAsDictionary[assignedGroupPermission.UserGroupId];
//clone the default permissions model to the assigned ones
defaultUserGroupPermissions.AssignedPermissions = AssignedUserGroupPermissions.ClonePermissions(defaultUserGroupPermissions.DefaultPermissions);
//since there is custom permissions assigned to this node for this group, we need to clear all of the default permissions
//and we'll re-check it if it's one of the explicitly assigned ones
foreach (var permission in defaultUserGroupPermissions.AssignedPermissions.SelectMany(x => x.Value))
{
permission.Checked = false;
permission.Checked = assignedGroupPermission.AssignedPermissions.Contains(permission.PermissionCode, StringComparer.InvariantCulture);
}
}
return defaultPermissionsByGroup;
}
/// <summary>
/// Returns an item to be used to display the recycle bin for content
/// </summary>
/// <returns></returns>
public ContentItemDisplay GetRecycleBin()
{
var apps = new List<ContentApp>();
apps.Add(ListViewContentAppFactory.CreateContentApp(Services.DataTypeService, _propertyEditors, "recycleBin", "content", Core.Constants.DataTypes.DefaultMembersListView));
apps[0].Active = true;
var display = new ContentItemDisplay
{
Id = Constants.System.RecycleBinContent,
ParentId = -1,
ContentTypeAlias = "recycleBin",
IsContainer = true,
Path = "-1," + Constants.System.RecycleBinContent,
Variants = new List<ContentVariantDisplay>
{
new ContentVariantDisplay
{
CreateDate = DateTime.Now,
Name = Services.TextService.Localize("general","recycleBin")
}
},
ContentApps = apps
};
return display;
}
public ContentItemDisplay GetBlueprintById(int id)
{
var foundContent = Services.ContentService.GetBlueprintById(id);
if (foundContent == null)
{
HandleContentNotFound(id);
}
var content = MapToDisplay(foundContent);
SetupBlueprint(content, foundContent);
return content;
}
private static void SetupBlueprint(ContentItemDisplay content, IContent persistedContent)
{
content.AllowPreview = false;
//set a custom path since the tree that renders this has the content type id as the parent
content.Path = string.Format("-1,{0},{1}", persistedContent.ContentTypeId, content.Id);
content.AllowedActions = new[] { "A" };
content.IsBlueprint = true;
// TODO: exclude the content apps here
//var excludeProps = new[] { "_umb_urls", "_umb_releasedate", "_umb_expiredate", "_umb_template" };
//var propsTab = content.Tabs.Last();
//propsTab.Properties = propsTab.Properties
// .Where(p => excludeProps.Contains(p.Alias) == false);
}
/// <summary>
/// Gets the content json for the content id
/// </summary>
/// <param name="id"></param>
/// <param name="culture"></param>
/// <returns></returns>
[OutgoingEditorModelEvent]
[EnsureUserPermissionForContent("id")]
public ContentItemDisplay GetById(int id)
{
var foundContent = GetObjectFromRequest(() => Services.ContentService.GetById(id));
if (foundContent == null)
{
HandleContentNotFound(id);
return null;//irrelevant since the above throws
}
var content = MapToDisplay(foundContent);
return content;
}
/// <summary>
/// Gets the content json for the content guid
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[OutgoingEditorModelEvent]
[EnsureUserPermissionForContent("id")]
public ContentItemDisplay GetById(Guid id)
{
var foundContent = GetObjectFromRequest(() => Services.ContentService.GetById(id));
if (foundContent == null)
{
HandleContentNotFound(id);
return null;//irrelevant since the above throws
}
var content = MapToDisplay(foundContent);
return content;
}
/// <summary>
/// Gets the content json for the content udi
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[OutgoingEditorModelEvent]
[EnsureUserPermissionForContent("id")]
public ContentItemDisplay GetById(Udi id)
{
var guidUdi = id as GuidUdi;
if (guidUdi != null)
{
return GetById(guidUdi.Guid);
}
throw new HttpResponseException(HttpStatusCode.NotFound);
}
/// <summary>
/// Gets an empty content item for the document type.
/// </summary>
/// <param name="contentTypeAlias"></param>
/// <param name="parentId"></param>
[OutgoingEditorModelEvent]
public ContentItemDisplay GetEmpty(string contentTypeAlias, int parentId)
{
var contentType = Services.ContentTypeService.Get(contentTypeAlias);
if (contentType == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return GetEmpty(contentType, parentId);
}
/// <summary>
/// Gets a dictionary containing empty content items for every alias specified in the contentTypeAliases array in the body of the request.
/// </summary>
/// <remarks>
/// This is a post request in order to support a large amount of aliases without hitting the URL length limit.
/// </remarks>
/// <param name="contentTypesByAliases"></param>
/// <returns></returns>
[OutgoingEditorModelEvent]
[HttpPost]
public IDictionary<string, ContentItemDisplay> GetEmptyByAliases(ContentTypesByAliases contentTypesByAliases)
{
// It's important to do this operation within a scope to reduce the amount of readlock queries.
using var scope = _scopeProvider.CreateScope(autoComplete: true);
var contentTypes = contentTypesByAliases.ContentTypeAliases.Select(alias => Services.ContentTypeService.Get(alias));
return GetEmpties(contentTypes, contentTypesByAliases.ParentId).ToDictionary(x => x.ContentTypeAlias);
}
/// <summary>
/// Gets an empty content item for the document type.
/// </summary>
/// <param name="contentTypeKey"></param>
/// <param name="parentId"></param>
[OutgoingEditorModelEvent]
public ContentItemDisplay GetEmptyByKey(Guid contentTypeKey, int parentId)
{
using (var scope = _scopeProvider.CreateScope())
{
var contentType = Services.ContentTypeService.Get(contentTypeKey);
if (contentType == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
var contentItem = GetEmpty(contentType, parentId);
scope.Complete();
return contentItem;
}
}
private ContentItemDisplay CleanContentItemDisplay(ContentItemDisplay display)
{
// translate the content type name if applicable
display.ContentTypeName = Services.TextService.UmbracoDictionaryTranslate(display.ContentTypeName);
// if your user type doesn't have access to the Settings section it would not get this property mapped
if (display.DocumentType != null)
display.DocumentType.Name = Services.TextService.UmbracoDictionaryTranslate(display.DocumentType.Name);
//remove the listview app if it exists
display.ContentApps = display.ContentApps.Where(x => x.Alias != "umbListView").ToList();
return display;
}
private ContentItemDisplay GetEmpty(IContentType contentType, int parentId)
{
var emptyContent = Services.ContentService.Create("", parentId, contentType, Security.GetUserId().ResultOr(0));
var mapped = MapToDisplay(emptyContent);
return CleanContentItemDisplay(mapped);
}
/// <summary>
/// Gets an empty <see cref="ContentItemDisplay"/> for each content type in the IEnumerable, all with the same parent ID
/// </summary>
/// <remarks>Will attempt to re-use the same permissions for every content as long as the path and user are the same</remarks>
/// <param name="contentTypes"></param>
/// <param name="parentId"></param>
/// <returns></returns>
private IEnumerable<ContentItemDisplay> GetEmpties(IEnumerable<IContentType> contentTypes, int parentId)
{
var result = new List<ContentItemDisplay>();
var userId = Security.GetUserId().ResultOr(0);
var currentUser = Security.CurrentUser;
// We know that if the ID is less than 0 the parent is null.
// Since this is called with parent ID it's safe to assume that the parent is the same for all the content types.
var parent = parentId > 0 ? Services.ContentService.GetById(parentId) : null;
// Since the parent is the same and the path used to get permissions is based on the parent we only have to do it once
var path = parent == null ? "-1" : parent.Path;
var permissions = new Dictionary<string, EntityPermissionSet>
{
[path] = Services.UserService.GetPermissionsForPath(currentUser, path)
};
foreach (var contentType in contentTypes)
{
var emptyContent = Services.ContentService.Create("", parentId, contentType, userId);
var mapped = MapToDisplay(emptyContent, context =>
{
// Since the permissions depend on current user and path, we add both of these to context as well,
// that way we can compare the path and current user when mapping, if they're the same just take permissions
// and skip getting them again, in theory they should always be the same, but better safe than sorry.,
context.Items["Parent"] = parent;
context.Items["CurrentUser"] = currentUser;
context.Items["Permissions"] = permissions;
});
result.Add(CleanContentItemDisplay(mapped));
}
return result;
}
private IDictionary<Guid, ContentItemDisplay> GetEmptyByKeysInternal(Guid[] contentTypeKeys, int parentId)
{
using var scope = _scopeProvider.CreateScope(autoComplete: true);
var contentTypes = Services.ContentTypeService.GetAll(contentTypeKeys).ToList();
return GetEmpties(contentTypes, parentId).ToDictionary(x => x.ContentTypeKey);
}
/// <summary>
/// Gets a collection of empty content items for all document types.
/// </summary>
/// <param name="contentTypeKeys"></param>
/// <param name="parentId"></param>
[OutgoingEditorModelEvent]
public IDictionary<Guid, ContentItemDisplay> GetEmptyByKeys([FromUri] Guid[] contentTypeKeys, [FromUri] int parentId)
{
return GetEmptyByKeysInternal(contentTypeKeys, parentId);
}
/// <summary>
/// Gets a collection of empty content items for all document types.
/// </summary>
/// <remarks>
/// This is a post request in order to support a large amount of GUIDs without hitting the URL length limit.
/// </remarks>
/// <param name="contentTypeByKeys"></param>
/// <returns></returns>
[HttpPost]
[OutgoingEditorModelEvent]
public IDictionary<Guid, ContentItemDisplay> GetEmptyByKeys(ContentTypesByKeys contentTypeByKeys)
{
return GetEmptyByKeysInternal(contentTypeByKeys.ContentTypeKeys, contentTypeByKeys.ParentId);
}
[OutgoingEditorModelEvent]
public ContentItemDisplay GetEmpty(int blueprintId, int parentId)
{
var blueprint = Services.ContentService.GetBlueprintById(blueprintId);
if (blueprint == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
blueprint.Id = 0;
blueprint.Name = string.Empty;
blueprint.ParentId = parentId;
var mapped = Mapper.Map<ContentItemDisplay>(blueprint);
//remove the listview app if it exists
mapped.ContentApps = mapped.ContentApps.Where(x => x.Alias != "umbListView").ToList();
return mapped;
}
/// <summary>
/// Gets the Url for a given node ID
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public HttpResponseMessage GetNiceUrl(int id)
{
var url = UmbracoContext.Url(id);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(url, Encoding.UTF8, "text/plain");
return response;
}
/// <summary>
/// Gets the Url for a given node ID
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public HttpResponseMessage GetNiceUrl(Guid id)
{
var url = UmbracoContext.Url(id);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(url, Encoding.UTF8, "text/plain");
return response;
}
/// <summary>
/// Gets the Url for a given node ID
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public HttpResponseMessage GetNiceUrl(Udi id)
{
var guidUdi = id as GuidUdi;
if (guidUdi != null)
{
return GetNiceUrl(guidUdi.Guid);
}
throw new HttpResponseException(HttpStatusCode.NotFound);
}
/// <summary>
/// Gets the children for the content id passed in
/// </summary>
/// <returns></returns>
[FilterAllowedOutgoingContent(typeof(IEnumerable<ContentItemBasic<ContentPropertyBasic>>), "Items")]
public PagedResult<ContentItemBasic<ContentPropertyBasic>> GetChildren(
int id,
int pageNumber = 0, // TODO: This should be '1' as it's not the index
int pageSize = 0,
string orderBy = "SortOrder",
Direction orderDirection = Direction.Ascending,
bool orderBySystemField = true,
string filter = "")
{
return GetChildren(id, null, pageNumber, pageSize, orderBy, orderDirection, orderBySystemField, filter);
}
/// <summary>
/// Gets the children for the content id passed in
/// </summary>
/// <returns></returns>
[FilterAllowedOutgoingContent(typeof(IEnumerable<ContentItemBasic<ContentPropertyBasic>>), "Items")]
public PagedResult<ContentItemBasic<ContentPropertyBasic>> GetChildren(
int id,
string includeProperties,
int pageNumber = 0,
int pageSize = 0,
string orderBy = "SortOrder",
Direction orderDirection = Direction.Ascending,
bool orderBySystemField = true,
string filter = "",
string cultureName = "") // TODO: it's not a NAME it's the ISO CODE
{
long totalChildren;
List<IContent> children;
// Sets the culture to the only existing culture if we only have one culture.
if (string.IsNullOrWhiteSpace(cultureName))
{
if (_allLangs.Value.Count == 1)
{
cultureName = _allLangs.Value.First().Key;
}
}
if (pageNumber > 0 && pageSize > 0)
{
IQuery<IContent> queryFilter = null;
if (filter.IsNullOrWhiteSpace() == false)
{
//add the default text filter
queryFilter = SqlContext.Query<IContent>()
.Where(x => x.Name.Contains(filter));
}
children = Services.ContentService
.GetPagedChildren(id, pageNumber - 1, pageSize, out totalChildren,
queryFilter,
Ordering.By(orderBy, orderDirection, cultureName, !orderBySystemField)).ToList();
}
else
{
//better to not use this without paging where possible, currently only the sort dialog does
children = Services.ContentService.GetPagedChildren(id, 0, int.MaxValue, out var total).ToList();
totalChildren = children.Count;
}
if (totalChildren == 0)
{
return new PagedResult<ContentItemBasic<ContentPropertyBasic>>(0, 0, 0);
}
var pagedResult = new PagedResult<ContentItemBasic<ContentPropertyBasic>>(totalChildren, pageNumber, pageSize);
pagedResult.Items = children.Select(content =>
Mapper.Map<IContent, ContentItemBasic<ContentPropertyBasic>>(content,
context =>
{
context.SetCulture(cultureName);
// if there's a list of property aliases to map - we will make sure to store this in the mapping context.
if (!includeProperties.IsNullOrWhiteSpace())
context.SetIncludedProperties(includeProperties.Split(new[] { ", ", "," }, StringSplitOptions.RemoveEmptyEntries));
}))
.ToList(); // evaluate now
return pagedResult;
}
/// <summary>
/// Creates a blueprint from a content item
/// </summary>
/// <param name="contentId">The content id to copy</param>
/// <param name="name">The name of the blueprint</param>
/// <returns></returns>
[EnsureUserPermissionForContent("contentId", ActionCreateBlueprintFromContent.ActionLetter)]
[HttpPost]
public SimpleNotificationModel CreateBlueprintFromContent([FromUri] int contentId, [FromUri] string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("Value cannot be null or whitespace.", nameof(name));
var content = Services.ContentService.GetById(contentId);
if (content == null)
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
EnsureUniqueName(name, content, nameof(name));
var blueprint = Services.ContentService.CreateContentFromBlueprint(content, name, Security.GetUserId().ResultOr(0));
Services.ContentService.SaveBlueprint(blueprint, Security.GetUserId().ResultOr(0));
var notificationModel = new SimpleNotificationModel();
notificationModel.AddSuccessNotification(
Services.TextService.Localize("blueprints", "createdBlueprintHeading"),
Services.TextService.Localize("blueprints", "createdBlueprintMessage", new[] { content.Name })
);
return notificationModel;
}
private void EnsureUniqueName(string name, IContent content, string modelName)
{
var existing = Services.ContentService.GetBlueprintsForContentTypes(content.ContentTypeId);
if (existing.Any(x => x.Name == name && x.Id != content.Id))
{
ModelState.AddModelError(modelName, Services.TextService.Localize("blueprints", "duplicateBlueprintMessage"));
throw new HttpResponseException(Request.CreateValidationErrorResponse(ModelState));
}
}
/// <summary>
/// Saves content
/// </summary>
/// <returns></returns>
[UmbracoTreeAuthorize(Constants.Trees.DocumentTypes)]
[FileUploadCleanupFilter]
[ContentSaveValidation(skipUserAccessValidation:true)] // skip user access validation because we "only" require Settings access to create new blueprints from scratch
public ContentItemDisplay PostSaveBlueprint([ModelBinder(typeof(BlueprintItemBinder))] ContentItemSave contentItem)
{
var contentItemDisplay = PostSaveInternal(contentItem,
content =>
{
EnsureUniqueName(content.Name, content, "Name");
Services.ContentService.SaveBlueprint(contentItem.PersistedContent, Security.CurrentUser.Id);
//we need to reuse the underlying logic so return the result that it wants
return OperationResult.Succeed(new EventMessages());
},
content =>
{
var display = MapToDisplay(content);
SetupBlueprint(display, content);
return display;
});
return contentItemDisplay;
}
/// <summary>
/// Saves content
/// </summary>
/// <returns></returns>
[FileUploadCleanupFilter]
[ContentSaveValidation]
[OutgoingEditorModelEvent]
public ContentItemDisplay PostSave([ModelBinder(typeof(ContentItemBinder))] ContentItemSave contentItem)
{
var contentItemDisplay = PostSaveInternal(
contentItem,
content => Services.ContentService.Save(contentItem.PersistedContent, Security.CurrentUser.Id),
MapToDisplay);
return contentItemDisplay;
}
private ContentItemDisplay PostSaveInternal(ContentItemSave contentItem, Func<IContent, OperationResult> saveMethod, Func<IContent, ContentItemDisplay> mapToDisplay)
{
//Recent versions of IE/Edge may send in the full client side file path instead of just the file name.
//To ensure similar behavior across all browsers no matter what they do - we strip the FileName property of all
//uploaded files to being *only* the actual file name (as it should be).
if (contentItem.UploadedFiles != null && contentItem.UploadedFiles.Any())
{
foreach (var file in contentItem.UploadedFiles)
{
file.FileName = Path.GetFileName(file.FileName);
}
}
//If we've reached here it means:
// * Our model has been bound
// * and validated
// * any file attachments have been saved to their temporary location for us to use
// * we have a reference to the DTO object and the persisted object
// * Permissions are valid
MapValuesForPersistence(contentItem);
var passesCriticalValidationRules = ValidateCriticalData(contentItem, out var variantCount);
//we will continue to save if model state is invalid, however we cannot save if critical data is missing.
if (!ModelState.IsValid)
{
//check for critical data validation issues, we can't continue saving if this data is invalid
if (!passesCriticalValidationRules)
{
//ok, so the absolute mandatory data is invalid and it's new, we cannot actually continue!
// add the model state to the outgoing object and throw a validation message
var forDisplay = mapToDisplay(contentItem.PersistedContent);
forDisplay.Errors = ModelState.ToErrorDictionary();
throw new HttpResponseException(Request.CreateValidationErrorResponse(forDisplay));
}
//if there's only one variant and the model state is not valid we cannot publish so change it to save
if (variantCount == 1)
{
switch (contentItem.Action)
{
case ContentSaveAction.Publish:
case ContentSaveAction.PublishWithDescendants:
case ContentSaveAction.PublishWithDescendantsForce:
case ContentSaveAction.SendPublish:
case ContentSaveAction.Schedule:
contentItem.Action = ContentSaveAction.Save;
break;
case ContentSaveAction.PublishNew:
case ContentSaveAction.PublishWithDescendantsNew:
case ContentSaveAction.PublishWithDescendantsForceNew:
case ContentSaveAction.SendPublishNew:
case ContentSaveAction.ScheduleNew:
contentItem.Action = ContentSaveAction.SaveNew;
break;
}
}
}
bool wasCancelled;
//used to track successful notifications
var globalNotifications = new SimpleNotificationModel();
var notifications = new Dictionary<string, SimpleNotificationModel>
{
//global (non variant specific) notifications
[string.Empty] = globalNotifications
};
//The default validation language will be either: The default languauge, else if the content is brand new and the default culture is
// not marked to be saved, it will be the first culture in the list marked for saving.
var defaultCulture = _allLangs.Value.Values.FirstOrDefault(x => x.IsDefault)?.IsoCode;
var cultureForInvariantErrors = CultureImpact.GetCultureForInvariantErrors(
contentItem.PersistedContent,
contentItem.Variants.Where(x => x.Save).Select(x => x.Culture).ToArray(),
defaultCulture);
switch (contentItem.Action)
{
case ContentSaveAction.Save:
case ContentSaveAction.SaveNew:
SaveAndNotify(contentItem, saveMethod, variantCount, notifications, globalNotifications, "editContentSavedText", "editVariantSavedText", cultureForInvariantErrors, out wasCancelled);
break;
case ContentSaveAction.Schedule:
case ContentSaveAction.ScheduleNew:
if (!SaveSchedule(contentItem, globalNotifications))
{
wasCancelled = false;
break;
}
SaveAndNotify(contentItem, saveMethod, variantCount, notifications, globalNotifications, "editContentScheduledSavedText", "editVariantSavedText", cultureForInvariantErrors, out wasCancelled);
break;
case ContentSaveAction.SendPublish:
case ContentSaveAction.SendPublishNew:
var sendResult = Services.ContentService.SendToPublication(contentItem.PersistedContent, Security.CurrentUser.Id);
wasCancelled = sendResult == false;
if (sendResult)
{
if (variantCount > 1)
{
var variantErrors = ModelState.GetVariantsWithErrors(cultureForInvariantErrors);
var validVariants = contentItem.Variants
.Where(x => x.Save && !variantErrors.Contains((x.Culture, x.Segment)))
.Select(x => (culture: x.Culture, segment: x.Segment));
foreach (var (culture, segment) in validVariants)
{
var variantName = GetVariantName(culture, segment);
AddSuccessNotification(notifications, culture, segment,
Services.TextService.Localize("speechBubbles", "editContentSendToPublish"),
Services.TextService.Localize("speechBubbles", "editVariantSendToPublishText", new[] { variantName }));
}
}
else if (ModelState.IsValid)
{
globalNotifications.AddSuccessNotification(
Services.TextService.Localize("speechBubbles", "editContentSendToPublish"),
Services.TextService.Localize("speechBubbles", "editContentSendToPublishText"));
}
}
break;
case ContentSaveAction.Publish:
case ContentSaveAction.PublishNew:
{
var publishStatus = PublishInternal(contentItem, defaultCulture, cultureForInvariantErrors, out wasCancelled, out var successfulCultures);
AddPublishStatusNotifications(new[] { publishStatus }, globalNotifications, notifications, successfulCultures);
}
break;
case ContentSaveAction.PublishWithDescendants:
case ContentSaveAction.PublishWithDescendantsNew:
{
if (!ValidatePublishBranchPermissions(contentItem, out var noAccess))
{
globalNotifications.AddErrorNotification(
Services.TextService.Localize(null,"publish"),
Services.TextService.Localize("publish", "invalidPublishBranchPermissions"));
wasCancelled = false;
break;
}
var publishStatus = PublishBranchInternal(contentItem, false, cultureForInvariantErrors, out wasCancelled, out var successfulCultures).ToList();
AddPublishStatusNotifications(publishStatus, globalNotifications, notifications, successfulCultures);
}
break;
case ContentSaveAction.PublishWithDescendantsForce:
case ContentSaveAction.PublishWithDescendantsForceNew:
{
if (!ValidatePublishBranchPermissions(contentItem, out var noAccess))
{
globalNotifications.AddErrorNotification(
Services.TextService.Localize(null,"publish"),
Services.TextService.Localize("publish", "invalidPublishBranchPermissions"));
wasCancelled = false;
break;
}
var publishStatus = PublishBranchInternal(contentItem, true, cultureForInvariantErrors, out wasCancelled, out var successfulCultures).ToList();
AddPublishStatusNotifications(publishStatus, globalNotifications, notifications, successfulCultures);
}
break;
default:
throw new ArgumentOutOfRangeException();
}
//get the updated model
var display = mapToDisplay(contentItem.PersistedContent);
//merge the tracked success messages with the outgoing model
display.Notifications.AddRange(globalNotifications.Notifications);
foreach (var v in display.Variants.Where(x => x.Language != null))
{
if (notifications.TryGetValue(v.Language.IsoCode, out var n))
v.Notifications.AddRange(n.Notifications);
}
//lastly, if it is not valid, add the model state to the outgoing object and throw a 400
HandleInvalidModelState(display, cultureForInvariantErrors);
if (wasCancelled)
{
AddCancelMessage(display);
if (IsCreatingAction(contentItem.Action))
{
//If the item is new and the operation was cancelled, we need to return a different
// status code so the UI can handle it since it won't be able to redirect since there
// is no Id to redirect to!
throw new HttpResponseException(Request.CreateValidationErrorResponse(display));
}
}
display.PersistedContent = contentItem.PersistedContent;
return display;
}
private void AddPublishStatusNotifications(IReadOnlyCollection<PublishResult> publishStatus, SimpleNotificationModel globalNotifications, Dictionary<string, SimpleNotificationModel> variantNotifications, string[] successfulCultures)
{
//global notifications
AddMessageForPublishStatus(publishStatus, globalNotifications, successfulCultures);
//variant specific notifications
foreach (var c in successfulCultures ?? Array.Empty<string>())
AddMessageForPublishStatus(publishStatus, variantNotifications.GetOrCreate(c), successfulCultures);
}
/// <summary>
/// Validates critical data for persistence and updates the ModelState and result accordingly
/// </summary>
/// <param name="contentItem"></param>
/// <param name="variantCount">Returns the total number of variants (will be one if it's an invariant content item)</param>
/// <returns></returns>
/// <remarks>
/// For invariant, the variants collection count will be 1 and this will check if that invariant item has the critical values for persistence (i.e. Name)
///
/// For variant, each variant will be checked for critical data for persistence and if it's not there then it's flags will be reset and it will not
/// be persisted. However, we also need to deal with the case where all variants don't pass this check and then there is nothing to save. This also deals
/// with removing the Name validation keys based on data annotations validation for items that haven't been marked to be saved.
/// </remarks>
/// <returns>
/// returns false if persistence cannot take place, returns true if persistence can take place even if there are validation errors
/// </returns>
private bool ValidateCriticalData(ContentItemSave contentItem, out int variantCount)
{
var variants = contentItem.Variants.ToList();
variantCount = variants.Count;
var savedCount = 0;
var variantCriticalValidationErrors = new List<string>();
for (var i = 0; i < variants.Count; i++)
{
var variant = variants[i];
if (variant.Save)
{
//ensure the variant has all critical required data to be persisted
if (!RequiredForPersistenceAttribute.HasRequiredValuesForPersistence(variant))
{
variantCriticalValidationErrors.Add(variant.Culture);
//if there's no Name, it cannot be persisted at all reset the flags, this cannot be saved or published
variant.Save = variant.Publish = false;
//if there's more than 1 variant, then we need to add the culture specific error
//messages based on the variants in error so that the messages show in the publish/save dialog
if (variants.Count > 1)
AddVariantValidationError(variant.Culture, variant.Segment, "publish","contentPublishedFailedByMissingName");
else
return false; //It's invariant and is missing critical data, it cannot be saved
}
savedCount++;
}
else
{
var msKey = $"Variants[{i}].Name";
if (ModelState.ContainsKey(msKey))
{
//if it's not being saved, remove the validation key
if (!variant.Save) ModelState.Remove(msKey);
}