-
Notifications
You must be signed in to change notification settings - Fork 461
/
ESContentletAPIImpl.java
10253 lines (8816 loc) · 462 KB
/
ESContentletAPIImpl.java
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
package com.dotcms.content.elasticsearch.business;
import com.dotcms.api.system.event.ContentletSystemEventUtil;
import com.dotcms.api.web.HttpServletRequestThreadLocal;
import com.dotcms.business.CloseDBIfOpened;
import com.dotcms.business.WrapInTransaction;
import com.dotcms.concurrent.DotConcurrentFactory;
import com.dotcms.concurrent.lock.IdentifierStripedLock;
import com.dotcms.content.elasticsearch.business.event.ContentletArchiveEvent;
import com.dotcms.content.elasticsearch.business.event.ContentletCheckinEvent;
import com.dotcms.content.elasticsearch.business.event.ContentletDeletedEvent;
import com.dotcms.content.elasticsearch.business.event.ContentletPublishEvent;
import com.dotcms.content.elasticsearch.constants.ESMappingConstants;
import com.dotcms.content.elasticsearch.util.ESUtils;
import com.dotcms.contenttype.business.BaseTypeToContentTypeStrategy;
import com.dotcms.contenttype.business.BaseTypeToContentTypeStrategyResolver;
import com.dotcms.contenttype.business.ContentTypeAPI;
import com.dotcms.contenttype.exception.NotFoundInDbException;
import com.dotcms.contenttype.model.field.BinaryField;
import com.dotcms.contenttype.model.field.CategoryField;
import com.dotcms.contenttype.model.field.ConstantField;
import com.dotcms.contenttype.model.field.DataTypes;
import com.dotcms.contenttype.model.field.FieldVariable;
import com.dotcms.contenttype.model.field.HostFolderField;
import com.dotcms.contenttype.model.field.JSONField;
import com.dotcms.contenttype.model.field.RelationshipField;
import com.dotcms.contenttype.model.field.TagField;
import com.dotcms.contenttype.model.type.BaseContentType;
import com.dotcms.contenttype.model.type.ContentType;
import com.dotcms.contenttype.model.type.ContentTypeIf;
import com.dotcms.contenttype.transform.contenttype.ContentTypeTransformer;
import com.dotcms.contenttype.transform.contenttype.StructureTransformer;
import com.dotcms.contenttype.transform.field.LegacyFieldTransformer;
import com.dotcms.exception.ExceptionUtil;
import com.dotcms.notifications.bean.NotificationLevel;
import com.dotcms.publisher.business.DotPublisherException;
import com.dotcms.publisher.business.PublisherAPI;
import com.dotcms.rendering.velocity.services.ContentletLoader;
import com.dotcms.rendering.velocity.services.PageLoader;
import com.dotcms.rest.AnonymousAccess;
import com.dotcms.rest.api.v1.temp.DotTempFile;
import com.dotcms.rest.api.v1.temp.TempFileAPI;
import com.dotcms.storage.FileMetadataAPI;
import com.dotcms.storage.model.Metadata;
import com.dotcms.system.event.local.business.LocalSystemEventsAPI;
import com.dotcms.system.event.local.type.content.CommitListenerEvent;
import com.dotcms.util.CollectionsUtils;
import com.dotcms.util.ConversionUtils;
import com.dotcms.util.DotPreconditions;
import com.dotcms.util.FunctionUtils;
import com.dotcms.util.JsonUtil;
import com.dotcms.util.ThreadContextUtil;
import com.dotcms.util.xstream.XStreamHandler;
import com.dotcms.variant.VariantAPI;
import com.dotcms.variant.model.Variant;
import com.dotmarketing.beans.Host;
import com.dotmarketing.beans.Identifier;
import com.dotmarketing.beans.MultiTree;
import com.dotmarketing.beans.Permission;
import com.dotmarketing.beans.Tree;
import com.dotmarketing.business.APILocator;
import com.dotmarketing.business.CacheLocator;
import com.dotmarketing.business.DotCacheException;
import com.dotmarketing.business.DotStateException;
import com.dotmarketing.business.FactoryLocator;
import com.dotmarketing.business.IdentifierAPI;
import com.dotmarketing.business.PermissionAPI;
import com.dotmarketing.business.RelationshipAPI;
import com.dotmarketing.business.Role;
import com.dotmarketing.business.Treeable;
import com.dotmarketing.business.UserAPI;
import com.dotmarketing.business.query.GenericQueryFactory.Query;
import com.dotmarketing.business.query.QueryUtil;
import com.dotmarketing.business.query.ValidationException;
import com.dotmarketing.cache.FieldsCache;
import com.dotmarketing.common.db.DotConnect;
import com.dotmarketing.common.model.ContentletSearch;
import com.dotmarketing.common.reindex.ReindexQueueAPI;
import com.dotmarketing.comparators.ContentMapComparator;
import com.dotmarketing.db.DbConnectionFactory;
import com.dotmarketing.db.FlushCacheRunnable;
import com.dotmarketing.db.HibernateUtil;
import com.dotmarketing.db.LocalTransaction;
import com.dotmarketing.exception.DoesNotExistException;
import com.dotmarketing.exception.DotDataException;
import com.dotmarketing.exception.DotHibernateException;
import com.dotmarketing.exception.DotRuntimeException;
import com.dotmarketing.exception.DotSecurityException;
import com.dotmarketing.exception.InvalidLicenseException;
import com.dotmarketing.factories.InodeFactory;
import com.dotmarketing.factories.MultiTreeAPI;
import com.dotmarketing.factories.PublishFactory;
import com.dotmarketing.factories.TreeFactory;
import com.dotmarketing.menubuilders.RefreshMenus;
import com.dotmarketing.portlets.categories.business.CategoryAPI;
import com.dotmarketing.portlets.categories.model.Category;
import com.dotmarketing.portlets.containers.model.Container;
import com.dotmarketing.portlets.contentlet.business.BinaryFileFilter;
import com.dotmarketing.portlets.contentlet.business.ContentletAPI;
import com.dotmarketing.portlets.contentlet.business.ContentletCache;
import com.dotmarketing.portlets.contentlet.business.DotContentletStateException;
import com.dotmarketing.portlets.contentlet.business.DotContentletValidationException;
import com.dotmarketing.portlets.contentlet.business.DotLockException;
import com.dotmarketing.portlets.contentlet.business.DotReindexStateException;
import com.dotmarketing.portlets.contentlet.business.HostAPI;
import com.dotmarketing.portlets.contentlet.model.Contentlet;
import com.dotmarketing.portlets.contentlet.model.ContentletDependencies;
import com.dotmarketing.portlets.contentlet.model.ContentletVersionInfo;
import com.dotmarketing.portlets.contentlet.model.IndexPolicy;
import com.dotmarketing.portlets.contentlet.util.ContentletUtil;
import com.dotmarketing.portlets.fileassets.business.FileAsset;
import com.dotmarketing.portlets.fileassets.business.FileAssetAPI;
import com.dotmarketing.portlets.fileassets.business.FileAssetValidationException;
import com.dotmarketing.portlets.fileassets.business.IFileAsset;
import com.dotmarketing.portlets.folders.business.FolderAPI;
import com.dotmarketing.portlets.folders.model.Folder;
import com.dotmarketing.portlets.htmlpageasset.business.HTMLPageAssetAPI;
import com.dotmarketing.portlets.htmlpageasset.business.HTMLPageAssetAPI.TemplateContainersReMap;
import com.dotmarketing.portlets.htmlpageasset.model.IHTMLPage;
import com.dotmarketing.portlets.languagesmanager.business.LanguageAPI;
import com.dotmarketing.portlets.languagesmanager.model.Language;
import com.dotmarketing.portlets.links.model.Link;
import com.dotmarketing.portlets.personas.model.Persona;
import com.dotmarketing.portlets.structure.business.FieldAPI;
import com.dotmarketing.portlets.structure.model.ContentletRelationships;
import com.dotmarketing.portlets.structure.model.ContentletRelationships.ContentletRelationshipRecords;
import com.dotmarketing.portlets.structure.model.Field;
import com.dotmarketing.portlets.structure.model.Field.FieldType;
import com.dotmarketing.portlets.structure.model.Relationship;
import com.dotmarketing.portlets.structure.model.Structure;
import com.dotmarketing.portlets.structure.transform.ContentletRelationshipsTransformer;
import com.dotmarketing.portlets.templates.model.Template;
import com.dotmarketing.portlets.workflows.business.WorkflowAPI;
import com.dotmarketing.portlets.workflows.business.WorkflowAPI.SystemAction;
import com.dotmarketing.portlets.workflows.model.WorkflowAction;
import com.dotmarketing.portlets.workflows.model.WorkflowComment;
import com.dotmarketing.portlets.workflows.model.WorkflowProcessor;
import com.dotmarketing.portlets.workflows.model.WorkflowTask;
import com.dotmarketing.tag.business.TagAPI;
import com.dotmarketing.tag.model.Tag;
import com.dotmarketing.util.ActivityLogger;
import com.dotmarketing.util.AdminLogger;
import com.dotmarketing.util.Config;
import com.dotmarketing.util.ConfigUtils;
import com.dotmarketing.util.DateUtil;
import com.dotmarketing.util.HostUtil;
import com.dotmarketing.util.InodeUtils;
import com.dotmarketing.util.Logger;
import com.dotmarketing.util.PageMode;
import com.dotmarketing.util.PaginatedArrayList;
import com.dotmarketing.util.RegEX;
import com.dotmarketing.util.RegExMatch;
import com.dotmarketing.util.TrashUtils;
import com.dotmarketing.util.UUIDGenerator;
import com.dotmarketing.util.UtilMethods;
import com.dotmarketing.util.WebKeys;
import com.dotmarketing.util.WebKeys.Relationship.RELATIONSHIP_CARDINALITY;
import com.dotmarketing.util.contentet.pagination.PaginatedContentletBuilder;
import com.dotmarketing.util.contentet.pagination.PaginatedContentlets;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.liferay.portal.NoSuchUserException;
import com.liferay.portal.language.LanguageException;
import com.liferay.portal.language.LanguageUtil;
import com.liferay.portal.model.User;
import com.liferay.util.FileUtil;
import com.liferay.util.StringPool;
import com.liferay.util.StringUtil;
import com.rainerhahnekamp.sneakythrow.Sneaky;
import com.thoughtworks.xstream.XStream;
import io.vavr.Lazy;
import io.vavr.Tuple2;
import io.vavr.control.Try;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchPhaseExecutionException;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.activation.MimeType;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.dotcms.exception.ExceptionUtil.bubbleUpException;
import static com.dotcms.exception.ExceptionUtil.getLocalizedMessageOrDefault;
import static com.dotmarketing.business.PermissionAPI.PERMISSION_CAN_ADD_CHILDREN;
import static com.dotmarketing.portlets.contentlet.model.Contentlet.URL_MAP_FOR_CONTENT_KEY;
import static com.dotmarketing.portlets.personas.business.PersonaAPI.DEFAULT_PERSONA_NAME_KEY;
/**
* Implementation class for the {@link ContentletAPI} interface.
*
* @author Jason Tesser
* @author David Torres
* @since 1.5
*/
public class ESContentletAPIImpl implements ContentletAPI {
private static final String CAN_T_CHANGE_STATE_OF_CHECKED_OUT_CONTENT = "Can't change state of checked out content or where inode is not set. Use Search or Find then use method";
private static final String CANT_GET_LOCK_ON_CONTENT = "Only the CMS Admin or the user who locked the contentlet can lock/unlock it";
private static final String FAILED_TO_DELETE_UNARCHIVED_CONTENT = "Failed to delete unarchived content. Content must be archived first before it can be deleted.";
private static final String NEVER_EXPIRE = "NeverExpire";
private static final String CHECKIN_IN_PROGRESS = "__checkin_in_progress__";
private static final String IS_NEW_CONTENT = "__IS_NEW_CONTENT__";
private final ContentletIndexAPIImpl indexAPI;
private final ESContentFactoryImpl contentFactory;
private final PermissionAPI permissionAPI;
private final CategoryAPI categoryAPI;
private final RelationshipAPI relationshipAPI;
private final FieldAPI fieldAPI;
private final LanguageAPI languageAPI;
private final ReindexQueueAPI reindexQueueAPI;
private final TagAPI tagAPI;
private final IdentifierStripedLock lockManager;
private final TempFileAPI tempApi;
private final FileMetadataAPI fileMetadataAPI;
private final Lazy<MultiTreeAPI> multiTreeAPI = Lazy.of(APILocator::getMultiTreeAPI);
public static final int MAX_LIMIT = 10000;
private static final boolean INCLUDE_DEPENDENCIES = true;
private static final String backupPath =
ConfigUtils.getBackupPath() + File.separator + "contentlets";
public static final String UNIQUE_PER_SITE_FIELD_VARIABLE_NAME = "uniquePerSite";
/**
* Property to fetch related content from database (only applies for relationship fields)
* Related content for legacy relationship will always be pulled from the index
*/
private static final boolean GET_RELATED_CONTENT_FROM_DB = Config
.getBooleanProperty("GET_RELATED_CONTENT_FROM_DB", true);
private final ContentletSystemEventUtil contentletSystemEventUtil;
private final LocalSystemEventsAPI localSystemEventsAPI;
private final BaseTypeToContentTypeStrategyResolver baseTypeToContentTypeStrategyResolver =
BaseTypeToContentTypeStrategyResolver.getInstance();
public enum QueryType {
search, suggest, moreLike, Facets
}
;
private static final Supplier<String> ND_SUPPLIER = () -> "N/D";
private ElasticReadOnlyCommand elasticReadOnlyCommand;
/**
* Default class constructor.
*/
@VisibleForTesting
public ESContentletAPIImpl(final ElasticReadOnlyCommand readOnlyCommand) {
indexAPI = new ContentletIndexAPIImpl();
fieldAPI = APILocator.getFieldAPI();
contentFactory = new ESContentFactoryImpl();
permissionAPI = APILocator.getPermissionAPI();
categoryAPI = APILocator.getCategoryAPI();
relationshipAPI = APILocator.getRelationshipAPI();
languageAPI = APILocator.getLanguageAPI();
reindexQueueAPI = APILocator.getReindexQueueAPI();
tagAPI = APILocator.getTagAPI();
contentletSystemEventUtil = ContentletSystemEventUtil.getInstance();
localSystemEventsAPI = APILocator.getLocalSystemEventsAPI();
lockManager = DotConcurrentFactory.getInstance().getIdentifierStripedLock();
tempApi = APILocator.getTempFileAPI();
this.elasticReadOnlyCommand = readOnlyCommand;
fileMetadataAPI = APILocator.getFileMetadataAPI();
}
public ESContentletAPIImpl() {
this(ElasticReadOnlyCommand.getInstance());
}
@Override
public SearchResponse esSearchRaw(String esQuery, boolean live, User user,
boolean respectFrontendRoles) throws DotSecurityException, DotDataException {
return APILocator.getEsSearchAPI().esSearchRaw(esQuery, live, user, respectFrontendRoles);
}
@Override
public ESSearchResults esSearch(String esQuery, boolean live, User user,
boolean respectFrontendRoles) throws DotSecurityException, DotDataException {
return APILocator.getEsSearchAPI().esSearch(esQuery, live, user, respectFrontendRoles);
}
@CloseDBIfOpened
@Override
public Object loadField(String inode, Field f) throws DotDataException {
return contentFactory.loadField(inode, f.getFieldContentlet());
}
@CloseDBIfOpened
public Object loadField(final String inode,
final com.dotcms.contenttype.model.field.Field field) throws DotDataException {
if (APILocator.getContentletJsonAPI().isPersistContentAsJson()) {
final Object value = contentFactory.loadJsonField(inode, field);
if (null != value) {
return value;
}
}
return contentFactory.loadField(inode, field.dbColumn());
}
@CloseDBIfOpened
@Override
public List<Contentlet> findAllContent(int offset, int limit) throws DotDataException {
return contentFactory.findAllCurrent(offset, limit);
}
@Override
public boolean isContentlet(String inode) throws DotDataException, DotRuntimeException {
Contentlet contentlet = new Contentlet();
try {
contentlet = find(inode, APILocator.getUserAPI().getSystemUser(), true);
} catch (DotSecurityException dse) {
throw new DotRuntimeException("Unable to use system user : ", dse);
} catch (Exception e) {
Logger.debug(this, "Inode unable to load as contentlet. Asssuming it is not content");
return false;
}
if (contentlet != null) {
if (InodeUtils.isSet(contentlet.getInode())) {
return true;
}
}
return false;
}
@CloseDBIfOpened
@Override
public Contentlet find(final String inode, final User user, final boolean respectFrontendRoles)
throws DotDataException, DotSecurityException {
final Contentlet contentlet = contentFactory.find(inode);
if (contentlet == null) {
return null;
}
if (this.permissionAPI.doesUserHavePermission(contentlet, PermissionAPI.PERMISSION_READ,
user,
respectFrontendRoles)) {
return contentlet;
} else {
final String userId = (user == null) ? "Unknown" : user.getUserId();
throw new DotSecurityException(
String.format("User '%s' does not have READ permissions on %s", userId,
ContentletUtil
.toShortString(contentlet)));
}
}
@Override
public Contentlet move(final Contentlet contentlet, final User user,
final String hostAndFolderPath,
final boolean respectFrontendRoles) throws DotSecurityException, DotDataException {
Logger.debug(this, () -> "Moving contentlet: " + contentlet.getIdentifier() + " to: "
+ hostAndFolderPath);
if (UtilMethods.isNotSet(hostAndFolderPath) || !hostAndFolderPath.startsWith(
HostUtil.HOST_INDICATOR)) {
throw new IllegalArgumentException("The host path is not valid: " + hostAndFolderPath);
}
final Tuple2<String, Host> hostPathTuple = Try.of(
() -> HostUtil.splitPathHost(hostAndFolderPath, user,
StringPool.FORWARD_SLASH)).getOrElseThrow(e -> new DotRuntimeException(e));
return this.move(contentlet, user, hostPathTuple._2(), hostPathTuple._1(),
respectFrontendRoles);
}
@Override
public Contentlet move(final Contentlet contentlet, final User user, final Host host,
final String folderPathParam,
final boolean respectFrontendRoles) throws DotSecurityException, DotDataException {
Logger.debug(this, () -> "Moving contentlet: " + contentlet.getIdentifier() + " to: "
+ folderPathParam);
if (UtilMethods.isNotSet(folderPathParam) || !folderPathParam.startsWith(
StringPool.SLASH)) {
throw new IllegalArgumentException("The folder is not valid: " + folderPathParam);
}
// we need a / at the end to check if exits
final String folderPath = folderPathParam.endsWith(StringPool.SLASH) ? folderPathParam
: folderPathParam + StringPool.SLASH;
//Check if the folder exists via Admin user, b/c user couldn't have VIEW Permissions over the folder
Folder folder = Try.of(() -> APILocator.getFolderAPI()
.findFolderByPath(folderPath, host, APILocator.systemUser(), respectFrontendRoles))
.getOrNull();
if (null == folder || !UtilMethods.isSet(folder.getInode())) {
// if the folder does not exists try, let's see if the current user can create it.
Logger.debug(this, () -> "On Moving Contentlet, creating the Folders: " + folderPath);
try {
// multiple contentlets on a bulk action may require to create the same folder
// if after release to block, the folder does not exists so create it
final String lockKey = folderPath;
folder = lockManager.tryLock(lockKey,
() -> {
Folder testFolder = Try.of(() -> APILocator.getFolderAPI()
.findFolderByPath(folderPath, host, user, respectFrontendRoles))
.getOrNull();
if (null == testFolder || !UtilMethods.isSet(testFolder.getInode())) {
Logger.debug(this,
() -> "Creating folders: " + folderPath + ", contentlet: "
+ contentlet.getIdentifier());
testFolder = DotConcurrentFactory.getInstance()
.getSingleSubmitter() // we need to run this in a separated thread, to use a diff conn.
.submit(() -> this.createFolder(folderPath, contentlet,
host, user, respectFrontendRoles))
.get(); // b.c the folder is a pre-requisites
}
return testFolder;
});
} catch (final Throwable t) {
Logger.warn(getClass(), t.getMessage(), t);
folder = null;
}
if (null == folder || !UtilMethods.isSet(folder.getInode())) {
throw new IllegalArgumentException(
"The folder does not exists: " + folderPath + " and could not be created");
}
}
return this.move(contentlet, user, host, folder, respectFrontendRoles);
}
@WrapInTransaction
private Folder createFolder(final String folderPath, final Contentlet contentlet,
final Host host,
final User user, final boolean respectFrontendRoles)
throws DotDataException, DotSecurityException {
Logger.debug(this, () -> "Creating folders: " + folderPath + ", contentlet: "
+ contentlet.getIdentifier());
return APILocator.getFolderAPI()
.createFolders(folderPath, host, user, respectFrontendRoles);
}
@WrapInTransaction
@Override
public Contentlet move(final Contentlet contentlet, final User incomingUser, final Host host,
final Folder folder,
final boolean respectFrontendRoles) throws DotSecurityException, DotDataException {
Logger.debug(this, () -> "Moving contentlet: " + contentlet.getIdentifier()
+ " to host: " + host.getHostname() + " and path: " + folder.getPath() + ", id: "
+ folder.getIdentifier());
final User user =
incomingUser != null ? incomingUser : APILocator.getUserAPI().getAnonymousUser();
if (user.isAnonymousUser() && AnonymousAccess.systemSetting() != AnonymousAccess.WRITE) {
throw new DotSecurityException(
"CONTENT_APIS_ALLOW_ANONYMOUS setting does not allow anonymous content WRITEs");
}
// if the user can write and add a children to the folder
if (!permissionAPI.doesUserHavePermission(contentlet, PermissionAPI.PERMISSION_WRITE, user,
respectFrontendRoles) ||
!permissionAPI.doesUserHavePermission(folder, PERMISSION_CAN_ADD_CHILDREN, user)) {
this.throwSecurityException(contentlet, user);
}
final Identifier identifier = APILocator.getIdentifierAPI()
.loadFromDb(contentlet.getIdentifier());
// if id exists
if (null == identifier || !UtilMethods.isSet(identifier.getId())) {
throw new DoesNotExistException(
"The identifier does not exists: " + contentlet.getIdentifier());
}
//Check if another content with the same name already exists in the new folder
if (APILocator.getFileAssetAPI().fileNameExists(host, folder, identifier.getAssetName(),
contentlet.getIdentifier())) {
throw new IllegalArgumentException(
"Content with the same name: '" + identifier.getAssetName()
+ "' already exists at the new path: " + host.getHostname()
+ folder.getPath());
}
// update with the new host and path
identifier.setHostId(host.getIdentifier());
identifier.setParentPath(folder.getPath());
Logger.debug(this, () -> "Updating the identifier: " + identifier);
// changing the host and path will move the contentlet
APILocator.getIdentifierAPI().save(identifier);
// update the version ts in order to be repushed
final Optional<ContentletVersionInfo> versionInfoOpt = APILocator.getVersionableAPI()
.getContentletVersionInfo(identifier.getId(), contentlet.getLanguageId());
if (versionInfoOpt.isPresent()) {
versionInfoOpt.get().setVersionTs(new Date());
APILocator.getVersionableAPI().saveContentletVersionInfo(versionInfoOpt.get());
}
// update the content host + folder
contentlet.setHost(host.getIdentifier());
contentlet.setFolder(folder.getInode());
// clean cache
HibernateUtil.addCommitListener(identifier.getId(), new FlushCacheRunnable() {
@Override
public void run() {
CacheLocator.getContentletCache().remove(contentlet.getInode());
}
});
// refresh the index based on the index policy
this.indexAPI.addContentToIndex(contentlet, false);
return contentlet;
}
@CloseDBIfOpened
@Override
public Optional<Contentlet> findInDb(final String inode) {
return contentFactory.findInDb(inode);
}
@CloseDBIfOpened
@Override
public List<Contentlet> findByStructure(String structureInode, User user,
boolean respectFrontendRoles, int limit, int offset)
throws DotDataException, DotSecurityException {
List<Contentlet> contentlets = contentFactory.findByStructure(structureInode, limit,
offset);
return permissionAPI.filterCollection(contentlets, PermissionAPI.PERMISSION_READ,
respectFrontendRoles, user);
}
@Override
public List<Contentlet> findByStructure(Structure structure, User user,
boolean respectFrontendRoles, int limit, int offset)
throws DotDataException, DotSecurityException {
return findByStructure(structure.getInode(), user, respectFrontendRoles, limit, offset);
}
@CloseDBIfOpened
@Override
public Contentlet findContentletForLanguage(long languageId, Identifier contentletId)
throws DotDataException, DotSecurityException {
try {
return findContentletByIdentifier(contentletId.getId(), false, languageId,
APILocator.systemUser(), false);
} catch (DotContentletStateException dcs) {
Logger.debug(this, () -> String.format(
"No working contentlet found for language: %d and identifier: %s ", languageId,
null != contentletId ? contentletId.getId() : "Unkown"));
}
return null;
}
public Contentlet findContentletByIdentifier(String identifier, boolean live, long languageId,
String variantId, User user, boolean respectFrontendRoles)
throws DotDataException, DotSecurityException, DotContentletStateException {
if (languageId <= 0) {
languageId = APILocator.getLanguageAPI().getDefaultLanguage().getId();
}
try {
Optional<ContentletVersionInfo> clvi = APILocator.getVersionableAPI()
.getContentletVersionInfo(identifier, languageId, variantId);
String liveInode = null;
String workingInode = null;
if (clvi.isPresent()) {
liveInode = clvi.get().getLiveInode();
workingInode = clvi.get().getWorkingInode();
}
if (live) {
return find(liveInode, user, respectFrontendRoles);
} else {
return find(workingInode, user, respectFrontendRoles);
}
} catch (DotSecurityException se) {
throw se;
} catch (Exception e) {
throw new DotContentletStateException(
"Can't find contentlet: " + identifier + " lang:" + languageId + " live:"
+ live, e);
}
}
@CloseDBIfOpened
@Override
public Contentlet findContentletByIdentifier(String identifier, boolean live, long languageId,
User user, boolean respectFrontendRoles)
throws DotDataException, DotSecurityException, DotContentletStateException {
return findContentletByIdentifier(identifier, live, languageId,
VariantAPI.DEFAULT_VARIANT.name(), user, respectFrontendRoles);
}
@CloseDBIfOpened
@Override
public Optional<Contentlet> findContentletByIdentifierOrFallback(final String identifier,
final boolean live,
final long incomingLangId, final User user, final boolean respectFrontendRoles) {
final long defaultLanguageId = this.languageAPI.getDefaultLanguage().getId();
final long tryLanguage = incomingLangId <= 0 ? defaultLanguageId : incomingLangId;
boolean fallback = false;
try {
// try the user language
Optional<ContentletVersionInfo> contentletVersionInfo =
APILocator.getVersionableAPI()
.getContentletVersionInfo(identifier, tryLanguage);
// try the fallback if does not exists
if (tryLanguage != defaultLanguageId && (contentletVersionInfo.isEmpty()
|| (live && contentletVersionInfo.get().getLiveInode() == null))) {
fallback = true; // using the fallback
contentletVersionInfo = APILocator.getVersionableAPI()
.getContentletVersionInfo(identifier, defaultLanguageId);
}
if (contentletVersionInfo.isEmpty()) {
return Optional.empty();
}
final Contentlet contentlet = live ?
this.find(contentletVersionInfo.get().getLiveInode(), user,
respectFrontendRoles) :
this.find(contentletVersionInfo.get().getWorkingInode(), user,
respectFrontendRoles);
if (null == contentlet) {
return Optional.empty();
}
// if we are using the fallback, and it is not allowed, return empty
if (fallback && tryLanguage != defaultLanguageId && !contentlet.getContentType()
.languageFallback()) {
return Optional.empty();
}
return Optional.of(contentlet);
} catch (Exception e) {
throw new DotContentletStateException(
"Can't find contentlet: " + identifier + " lang:" + incomingLangId + " live:"
+ live, e);
}
}
@CloseDBIfOpened
@Override
public Contentlet findContentletByIdentifierAnyLanguage(final String identifier,
final boolean includeDeleted) throws DotDataException {
try {
return contentFactory.findContentletByIdentifierAnyLanguage(identifier, includeDeleted);
} catch (Exception e) {
throw new DotContentletStateException("Can't find contentlet: " + identifier, e);
}
}
@CloseDBIfOpened
@Override
public Contentlet findContentletByIdentifierAnyLanguage(final String identifier)
throws DotDataException {
try {
return contentFactory.findContentletByIdentifierAnyLanguage(identifier);
} catch (Exception e) {
throw new DotContentletStateException("Can't find contentlet: " + identifier, e);
}
}
@CloseDBIfOpened
@Override
public Contentlet findContentletByIdentifierAnyLanguageAnyVariant(final String identifier) throws DotDataException{
try {
final ContentletVersionInfo anyContentletVersionInfoAnyVariant = FactoryLocator.getVersionableFactory()
.findAnyContentletVersionInfoAnyVariant(identifier, false)
.orElseThrow(() -> new NotFoundInDbException("Contentlet does not exists"));
return contentFactory.find(anyContentletVersionInfoAnyVariant.getWorkingInode());
} catch (Exception e) {
throw new DotContentletStateException("Can't find contentlet: " + identifier, e);
}
}
@CloseDBIfOpened
@Override
public Contentlet findContentletByIdentifierAnyLanguage(final String identifier, final String variant) throws DotDataException {
return findContentletByIdentifierAnyLanguage(identifier, variant, false);
}
@CloseDBIfOpened
@Override
public Contentlet findContentletByIdentifierAnyLanguage(final String identifier, final String variant,
final boolean includeDeleted) throws DotDataException{
try {
return contentFactory.findContentletByIdentifierAnyLanguage(identifier, variant, includeDeleted);
} catch (Exception e) {
throw new DotContentletStateException("Can't find contentlet: " + identifier, e);
}
}
@CloseDBIfOpened
@Override
public List<Contentlet> findContentletsByIdentifiers(final String[] identifiers,
final boolean live, final long languageId, final User user,
final boolean respectFrontendRoles)
throws DotDataException, DotSecurityException, DotContentletStateException {
final List<Contentlet> contentlets = new ArrayList<>();
for (final String identifier : identifiers) {
final Contentlet contentlet = findContentletByIdentifier(identifier.trim(), live,
languageId, user, respectFrontendRoles);
contentlets.add(contentlet);
}
return contentlets;
}
@CloseDBIfOpened
@Override
public List<Contentlet> findContentlets(List<String> inodes)
throws DotDataException, DotSecurityException {
return contentFactory.findContentlets(inodes);
}
@CloseDBIfOpened
@Override
public List<Contentlet> findContentletsByFolder(Folder parentFolder, User user,
boolean respectFrontendRoles) throws DotDataException, DotSecurityException {
try {
return permissionAPI.filterCollection(
search("+conFolder:" + parentFolder.getInode(), -1, 0, null, user,
respectFrontendRoles), PermissionAPI.PERMISSION_READ,
respectFrontendRoles, user);
} catch (Exception e) {
Logger.error(this.getClass(), e.getMessage(), e);
throw new DotRuntimeException(e.getMessage(), e);
}
}
@CloseDBIfOpened
@Override
public List<Contentlet> findContentletsByHost(Host parentHost, User user,
boolean respectFrontendRoles) throws DotDataException, DotSecurityException {
try {
return permissionAPI.filterCollection(
search("+conHost:" + parentHost.getIdentifier() + " +working:true", -1, 0, null,
user, respectFrontendRoles), PermissionAPI.PERMISSION_READ,
respectFrontendRoles, user);
} catch (Exception e) {
Logger.error(this.getClass(), e.getMessage(), e);
throw new DotRuntimeException(e.getMessage(), e);
}
}
@CloseDBIfOpened
@Override
public PaginatedContentlets findContentletsPaginatedByHost(Host parentHost, User user,
boolean respectFrontendRoles) throws DotDataException, DotSecurityException {
return findContentletsPaginatedByHost(parentHost, null, null, user, respectFrontendRoles);
}
public PaginatedContentlets findContentletsPaginatedByHost(final Host parentHost,
final List<Integer> includingContentTypes,
final List<Integer> excludingContentTypes,
final User user,
final boolean respectFrontendRoles) throws DotDataException, DotSecurityException {
final String query = getContentletByHostQuery(parentHost, includingContentTypes,
excludingContentTypes);
return new PaginatedContentletBuilder()
.setLuceneQuery(query)
.setUser(user)
.setRespectFrontendRoles(respectFrontendRoles)
.build();
}
@CloseDBIfOpened
@Override
public List<Contentlet> findContentletsByHost(Host parentHost,
List<Integer> includingContentTypes, List<Integer> excludingContentTypes, User user,
boolean respectFrontendRoles) throws DotDataException, DotSecurityException {
try {
final String query = getContentletByHostQuery(parentHost, includingContentTypes,
excludingContentTypes);
return permissionAPI.filterCollection(
search(query, -1, 0, null, user, respectFrontendRoles),
PermissionAPI.PERMISSION_READ, respectFrontendRoles, user);
} catch (Exception e) {
Logger.error(this.getClass(), e.getMessage(), e);
throw new DotRuntimeException(e.getMessage(), e);
}
}
private String getContentletByHostQuery(Host parentHost, List<Integer> includingContentTypes,
List<Integer> excludingContentTypes) {
final StringBuilder query = new StringBuilder();
query.append("+conHost:").append(parentHost.getIdentifier()).append(" +working:true");
// Including content types
if (includingContentTypes != null && !includingContentTypes.isEmpty()) {
query.append(" +structureType:(").append(StringUtils.join(includingContentTypes, " "))
.append(")");
}
// Excluding content types
if (excludingContentTypes != null && !excludingContentTypes.isEmpty()) {
query.append(" -structureType:(").append(StringUtils.join(excludingContentTypes, " "))
.append(")");
}
return query.toString();
}
@CloseDBIfOpened
@Override
public List<Contentlet> findContentletsByHostBaseType(Host parentHost,
List<Integer> includingBaseTypes, User user, boolean respectFrontendRoles)
throws DotDataException, DotSecurityException {
try {
StringBuilder query = new StringBuilder();
query.append("+conHost:").append(parentHost.getIdentifier()).append(" +working:true");
// Including content types
if (includingBaseTypes != null && !includingBaseTypes.isEmpty()) {
query.append(" +baseType:(").append(StringUtils.join(includingBaseTypes, " "))
.append(")");
}
return permissionAPI.filterCollection(
search(query.toString(), -1, 0, null, user, respectFrontendRoles),
PermissionAPI.PERMISSION_READ, respectFrontendRoles, user);
} catch (Exception e) {
Logger.error(this.getClass(), e.getMessage(), e);
throw new DotRuntimeException(e.getMessage(), e);
}
}
// note: is not annotated with WrapInTransaction b/c it handles his own transaction locally in the method
@WrapInTransaction
@Override
public void publish(final Contentlet contentlet, final User userIn,
final boolean respectFrontendRoles)
throws DotSecurityException, DotDataException, DotStateException {
final User user = (userIn != null) ? userIn : APILocator.getUserAPI().getAnonymousUser();
String contentPushPublishDate = contentlet.getStringProperty(
Contentlet.WORKFLOW_PUBLISH_DATE);
String contentPushExpireDate = contentlet.getStringProperty("wfExpireDate");
contentPushPublishDate =
UtilMethods.isSet(contentPushPublishDate) ? contentPushPublishDate : "N/D";
contentPushExpireDate =
UtilMethods.isSet(contentPushExpireDate) ? contentPushExpireDate : "N/D";
ActivityLogger.logInfo(getClass(), "Publishing Content",
"StartDate: " + contentPushPublishDate + "; "
+ "EndDate: " + contentPushExpireDate + "; User:" + (user != null
? user.getUserId() : "Unknown")
+ "; ContentIdentifier: " + (contentlet != null ? contentlet.getIdentifier()
: "Unknown"), contentlet.getHost());
try {
final Optional<Contentlet> contentletOpt = this.checkAndRunPublishAsWorkflow(contentlet,
user, respectFrontendRoles);
if (contentletOpt.isPresent()) {
Logger.debug(this, "A Workflow has been run instead of a simple publish: " +
contentlet.getIdentifier());
if (!contentlet.getInode().equals(contentletOpt.get().getInode())) {
this.copyProperties(contentlet, contentletOpt.get().getMap());
}
return;
}
this.internalPublish(contentlet, user, respectFrontendRoles);
} catch (DotDataException | DotStateException | DotSecurityException e) {
ActivityLogger.logInfo(getClass(), "Error Publishing Content",
"StartDate: " + contentPushPublishDate + "; "
+ "EndDate: " + contentPushExpireDate + "; User:" + (user != null
? user.getUserId() : "Unknown")
+ "; ContentIdentifier: " + (contentlet != null
? contentlet.getIdentifier() : "Unknown"), contentlet.getHost());
throw e;
}
ActivityLogger.logInfo(getClass(), "Content Published",
"StartDate: " + contentPushPublishDate + "; "
+ "EndDate: " + contentPushExpireDate + "; User:" + (user != null
? user.getUserId() : "Unknown")
+ "; ContentIdentifier: " + (contentlet != null ? contentlet.getIdentifier()
: "Unknown"), contentlet.getHost());
//Generate a System Event for this publish operation
HibernateUtil.addCommitListener(
() -> this.contentletSystemEventUtil.pushPublishEvent(contentlet), 1000);
}
private void internalPublish(final Contentlet contentlet, final User user,
final boolean respectFrontendRoles) throws DotDataException, DotSecurityException {
if (StringPool.BLANK.equals(contentlet.getInode())) {
throw new DotContentletStateException(CAN_T_CHANGE_STATE_OF_CHECKED_OUT_CONTENT);
}
if (!permissionAPI.doesUserHavePermission(contentlet, PermissionAPI.PERMISSION_PUBLISH,
user, respectFrontendRoles)) {
Logger.debug(PublishFactory.class,
() -> "publishAsset: user = " + (user != null ? user.getEmailAddress()
: "Unknown")
+ ", don't have permissions to publish: " + (contentlet != null
? contentlet.getInode() : "Unknown"));
//If the contentlet has CMS Owner Publish permission on it, the user creating the new contentlet is allowed to publish
List<Role> roles = permissionAPI.getRoles(contentlet.getPermissionId(),
PermissionAPI.PERMISSION_PUBLISH, Role.CMS_OWNER_ROLE, 0, -1);
if (roles.isEmpty() &&
isNewContentlet(contentlet)) {
roles = permissionAPI.getRoles(contentlet.getContentType().getPermissionId(),
PermissionAPI.PERMISSION_PUBLISH, Role.CMS_OWNER_ROLE, 0, -1);
}
final Role cmsOwner = APILocator.getRoleAPI().loadCMSOwnerRole();
if (roles.size() > 0) {
final boolean isCMSOwner = roles.stream().anyMatch(cmsOwner::equals);
if (!isCMSOwner) {