-
Notifications
You must be signed in to change notification settings - Fork 461
/
BrowserAjax.java
2257 lines (1931 loc) · 89.2 KB
/
BrowserAjax.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.dotmarketing.portlets.browser.ajax;
import static com.dotmarketing.business.PermissionAPI.PERMISSION_CAN_ADD_CHILDREN;
import static com.dotmarketing.business.PermissionAPI.PERMISSION_PUBLISH;
import static com.dotmarketing.business.PermissionAPI.PERMISSION_READ;
import static com.dotmarketing.business.PermissionAPI.PERMISSION_WRITE;
import com.dotcms.contenttype.business.ContentTypeAPI;
import com.dotcms.contenttype.exception.NotFoundInDbException;
import com.dotcms.rendering.velocity.viewtools.BrowserAPI;
import com.dotcms.repackage.org.directwebremoting.WebContext;
import com.dotcms.repackage.org.directwebremoting.WebContextFactory;
import com.dotmarketing.beans.Host;
import com.dotmarketing.beans.Identifier;
import com.dotmarketing.beans.Inode;
import com.dotmarketing.beans.WebAsset;
import com.dotmarketing.business.APILocator;
import com.dotmarketing.business.CacheLocator;
import com.dotmarketing.business.DotStateException;
import com.dotmarketing.business.IdentifierAPI;
import com.dotmarketing.business.PermissionAPI;
import com.dotmarketing.business.Role;
import com.dotmarketing.business.VersionableAPI;
import com.dotmarketing.business.util.HostNameComparator;
import com.dotmarketing.business.web.HostWebAPI;
import com.dotmarketing.business.web.UserWebAPI;
import com.dotmarketing.business.web.WebAPILocator;
import com.dotmarketing.db.HibernateUtil;
import com.dotmarketing.exception.DotDataException;
import com.dotmarketing.exception.DotHibernateException;
import com.dotmarketing.exception.DotRuntimeException;
import com.dotmarketing.exception.DotSecurityException;
import com.dotmarketing.factories.InodeFactory;
import com.dotmarketing.factories.PublishFactory;
import com.dotmarketing.factories.WebAssetFactory;
import com.dotmarketing.portlets.contentlet.business.ContentletAPI;
import com.dotmarketing.portlets.contentlet.business.HostAPI;
import com.dotmarketing.portlets.contentlet.model.Contentlet;
import com.dotmarketing.portlets.contentlet.model.ContentletVersionInfo;
import com.dotmarketing.portlets.fileassets.business.FileAsset;
import com.dotmarketing.portlets.fileassets.business.FileAssetAPI;
import com.dotmarketing.portlets.folders.business.FolderAPI;
import com.dotmarketing.portlets.folders.exception.InvalidFolderNameException;
import com.dotmarketing.portlets.folders.model.Folder;
import com.dotmarketing.portlets.htmlpageasset.model.HTMLPageAsset;
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.factories.LinkFactory;
import com.dotmarketing.portlets.links.model.Link;
import com.dotmarketing.portlets.structure.model.Structure;
import com.dotmarketing.portlets.workflows.business.WorkflowAPI;
import com.dotmarketing.portlets.workflows.model.WorkflowAction;
import com.dotmarketing.util.Config;
import com.dotmarketing.util.InodeUtils;
import com.dotmarketing.util.Logger;
import com.dotmarketing.util.UtilMethods;
import com.dotmarketing.util.WebKeys;
import com.liferay.portal.PortalException;
import com.liferay.portal.SystemException;
import com.liferay.portal.language.LanguageException;
import com.liferay.portal.language.LanguageUtil;
import com.liferay.portal.model.User;
import com.liferay.portal.struts.ActionException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
*
* @author david
*
*/
public class BrowserAjax {
private static PermissionAPI permissionAPI = APILocator.getPermissionAPI();
private UserWebAPI userAPI = WebAPILocator.getUserWebAPI();
private HostAPI hostAPI = APILocator.getHostAPI();
private HostWebAPI hostWebAPI = WebAPILocator.getHostWebAPI();
private FolderAPI folderAPI = APILocator.getFolderAPI();
private ContentletAPI contentletAPI = APILocator.getContentletAPI();
private LanguageAPI languageAPI = APILocator.getLanguageAPI();
private BrowserAPI browserAPI = new BrowserAPI();
private VersionableAPI versionAPI = APILocator.getVersionableAPI();
private IdentifierAPI identifierAPI = APILocator.getIdentifierAPI();
String activeHostId = "";
volatile String activeFolderInode = "";
private static String SELECTED_BROWSER_PATH_OBJECT = "SELECTED_BROWSER_PATH_OBJECT";
List<String> openFolders = new ArrayList<String> ();
String lastSortBy = "name";
boolean lastSortDirectionDesc = false;
/**
* @param permissionAPI the permissionAPI to set
*/
public static void setPermissionAPI(PermissionAPI permissionAPI) {
BrowserAjax.permissionAPI = permissionAPI;
}
private String getCurrentHost() {
final WebContext ctx = WebContextFactory.get();
final String selectedHost = (String) ctx.getHttpServletRequest().getSession().getAttribute(com.dotmarketing.util.WebKeys.CMS_SELECTED_HOST_ID);
if(selectedHost==null) {
// this will fire a host switch host if needed
ctx.getHttpServletRequest().getSession().setAttribute(com.dotmarketing.util.WebKeys.CMS_SELECTED_HOST_ID,WebAPILocator.getHostWebAPI().getCurrentHostNoThrow(ctx.getHttpServletRequest()).getIdentifier());
}
return selectedHost;
}
/**
* This methods is used to load the entire tree by first time.
* @return The whole folders tree structure.
* @throws DotDataException
* @throws DotSecurityException
*/
public List<Map> getTree(String hostId) throws DotDataException, DotSecurityException {
hostId = UtilMethods.isSet(hostId) ? hostId : getCurrentHost();
WebContext ctx = WebContextFactory.get();
User usr = getUser(ctx.getHttpServletRequest());
User systemUser = userAPI.getSystemUser();
Role[] roles = new Role[]{};
try {
roles = com.dotmarketing.business.APILocator.getRoleAPI().loadRolesForUser(usr.getUserId()).toArray(new Role[0]);
} catch (DotDataException e1) {
Logger.error(BrowserAjax.class,e1.getMessage(),e1);
}
List<Host> hosts=new ArrayList<Host>();
if(!UtilMethods.isSet(hostId) || hostId.equals("allHosts")){
hostId = "allHosts";
hosts.addAll(hostAPI.findAll(usr, false));
}
else{
hosts.add(hostAPI.find(hostId, usr, false));
}
List<Map> retList = new ArrayList<Map>();
for (Host host : hosts) {
//Ignore system host
if(host.isSystemHost()||host.isArchived())
continue;
//Obtain maps from hosts to be returned by ajax
Map<String,Object> hostMap = (Map<String,Object>)host.getMap();
if (activeHostId.equalsIgnoreCase(host.getIdentifier())|| hosts.size()==1 ) {
hostMap.put("open", true);
List<Map> children = getFoldersTree (host, roles);
hostMap.put("childrenFolders", children);
hostMap.put("childrenFoldersCount", children.size());
} else {
hostMap.put("open", false);
// hostMap.put("childrenFoldersCount", getSubFoldersCount(host));
}
java.util.List permissions = new ArrayList();
try {
permissions = permissionAPI.getPermissionIdsFromRoles(host, roles, usr);
} catch (DotDataException e) {
Logger.error(this, "Could not load permissions : ",e);
}
hostMap.put("permissions", permissions);
retList.add(hostMap);
}
return retList;
}
/**
* Action called every time a user opens a folder using the + (left hand side)
* @param hostId
* @return The subtree structure of folders
* @throws SystemException
* @throws PortalException
* @throws DotSecurityException
* @throws DotDataException
*/
public List<Map> openHostTree (String hostId) throws PortalException, SystemException, DotDataException, DotSecurityException {
WebContext ctx = WebContextFactory.get();
User usr = getUser(ctx.getHttpServletRequest());
boolean respectFrontend = !userAPI.isLoggedToBackend(ctx.getHttpServletRequest());
Host host = hostAPI.find(hostId, usr, respectFrontend);
if(! UtilMethods.isSet(hostId) || host == null){
Host browseHost = hostAPI.find(hostId, APILocator.getUserAPI().getSystemUser(), respectFrontend);
if(browseHost != null){
Logger.warn(this, "User " + usr.getUserId() + " cannot browse host id " + hostId + " aka "+ browseHost.getHostname());
}
else{
Logger.warn(this, "User " + usr.getUserId() + " cannot browse host id " + hostId );
}
return new ArrayList<Map>();
}
activeHostId = hostId;
Role[] roles = new Role[]{};
try {
roles = com.dotmarketing.business.APILocator.getRoleAPI().loadRolesForUser(usr.getUserId()).toArray(new Role[0]);
} catch (DotDataException e) {
Logger.error(BrowserAjax.class,e.getMessage(),e);
}
return getFoldersTree (host, roles);
}
/**
* Action called every time a user opens a folder using the + (left hand side)
* @param parentInode Parent folder to be opened
* @return The subtree structure of folders
* @throws DotDataException
* @throws DotSecurityException
* @throws DotHibernateException
*/
public List<Map> openFolderTree (String parentInode) throws DotHibernateException, DotSecurityException, DotDataException {
WebContext ctx = WebContextFactory.get();
User usr = getUser(ctx.getHttpServletRequest());
Role[] roles = new Role[]{};
if(usr != null){
try {
roles = com.dotmarketing.business.APILocator.getRoleAPI().loadRolesForUser(usr.getUserId()).toArray(new Role[0]);
}catch (NullPointerException e) {
Logger.debug(this, "array was null");
} catch (DotDataException e) {
Logger.error(BrowserAjax.class,e.getMessage(),e);
}
}
Folder f = (Folder) APILocator.getFolderAPI().find(parentInode, usr, false);
openFolders.add(parentInode);
return getFoldersTree (f, roles);
}
/**
* Action called everytime a user closes a folder using the - (left hand side)
* @param parentInode Parent folder to be opened
* @return The subtree structure of folders
*/
public void closeFolderTree (String parentInode) {
openFolders.remove(parentInode);
}
@SuppressWarnings("unchecked")
public List<Map<String, Object>> openFolderContent (String parentInode, String sortBy, boolean showArchived, long languageId) throws DotHibernateException, DotSecurityException, DotDataException {
activeFolderInode = parentInode;
this.lastSortBy = sortBy;
if (sortBy != null && UtilMethods.isSet(sortBy)) {
if (sortBy.equals(lastSortBy)) {
this.lastSortDirectionDesc = !this.lastSortDirectionDesc;
}
this.lastSortBy = sortBy;
}
List<Map<String, Object>> listToReturn;
try {
Map<String, Object> resultsMap = getFolderContent(parentInode, 0, -1, "", null, null, showArchived, false, false, this.lastSortBy, this.lastSortDirectionDesc, languageId);
listToReturn = (List<Map<String, Object>>) resultsMap.get("list");
} catch ( NotFoundInDbException e ){
Logger.error( this, "Please refresh the screen you opened this Folder from.", e );
listToReturn = new ArrayList<>();
}
return listToReturn;
}
public Map<String, Object> getFolderContent (String folderId, int offset, int maxResults, String filter, List<String> mimeTypes,
List<String> extensions, boolean showArchived, boolean noFolders, boolean onlyFiles, String sortBy, boolean sortByDesc, boolean excludeLinks, long languageId) throws DotHibernateException, DotSecurityException, DotDataException {
WebContext ctx = WebContextFactory.get();
HttpServletRequest req = ctx.getHttpServletRequest();
User usr = getUser(req);
HttpSession session = ctx.getSession();
Map<String, Object> selectedBrowserPathObject = new HashMap<String, Object>();
if(UtilMethods.isSet(folderId)){
selectedBrowserPathObject.put("path", getSelectedBrowserPathArray(folderId));
try {
selectedBrowserPathObject.put("currentFolder", getFolderMap(folderId));
} catch (Exception e) {}
session.setAttribute(SELECTED_BROWSER_PATH_OBJECT, selectedBrowserPathObject);
}
req.getSession().setAttribute(WebKeys.LANGUAGE_SEARCHED, String.valueOf(languageId));
return browserAPI.getFolderContent(usr, folderId, offset, maxResults, filter, mimeTypes, extensions, showArchived, noFolders, onlyFiles, sortBy, sortByDesc, excludeLinks, languageId);
}
private String[] getSelectedBrowserPathArray(String folderId) {
List<String> selectedPath = new ArrayList<String>();
Folder parentFolder = new Folder();
String[] pathArray = new String[]{"root"};
try{
User systemUser = APILocator.getUserAPI().getSystemUser();
selectedPath.add(folderId);
String hostId = folderAPI.find(folderId, systemUser, false).getHostId();
while(parentFolder != null){
parentFolder = folderAPI.findParentFolder(folderAPI.find(folderId, systemUser, false), systemUser, false);
if(parentFolder != null){
selectedPath.add(parentFolder.getInode());
folderId = parentFolder.getInode();
}else{
break;
}
}
pathArray = new String[selectedPath.size()+2];
int index = 0;
for(int i = selectedPath.size()+1; i > 1 ; i--){
pathArray[i] = selectedPath.get(index);
index++;
}
pathArray[0] = "root";
pathArray[1] = hostId;
}catch(Exception e){}
return pathArray;
}
public Map<String, Object> getFolderContent (String folderId, int offset, int maxResults, String filter, List<String> mimeTypes,
List<String> extensions, boolean showArchived, boolean noFolders, boolean onlyFiles, String sortBy, boolean sortByDesc, long languageId) throws DotHibernateException, DotSecurityException, DotDataException {
WebContext ctx = WebContextFactory.get();
HttpServletRequest req = ctx.getHttpServletRequest();
User usr = getUser(req);
req.getSession().setAttribute(WebKeys.LANGUAGE_SEARCHED, String.valueOf(languageId));
return browserAPI.getFolderContent(usr, folderId, offset, maxResults, filter, mimeTypes, extensions, showArchived, noFolders, onlyFiles, sortBy, sortByDesc, languageId);
}
/**
* Retrieves the list of contents under the specified folder. This specific
* implementation will only have one identifier per entry. This means that,
* for elements such as the new content pages, the list will not contain all
* the entries for all the available languages, but only the page in the
* default language, or the page in the next available language (one single
* entry per identifier).
*
* @param folderId
* - The identifier of the folder whose contents will be
* retrieved.
* @param offset
* - The result offset.
* @param maxResults
* - The maximum amount of results to return.
* @param filter
* - The parameter used to filter the results.
* @param mimeTypes
* - The allowed MIME types.
* @param extensions
* - The allowed extensions.
* @param showArchived
* - If <code>true</code>, retrieve archived elements too.
* Otherwise, set to <code>false</code>.
* @param noFolders
* - If <code>true</code>, retrieve everything except for
* folders. Otherwise, set to <code>false</code>.
* @param onlyFiles
* - If <code>true</code>, retrieve only file elements.
* Otherwise, set to <code>false</code>.
* @param sortBy
* - The sorting parameter.
* @param sortByDesc
* @param excludeLinks
* - If <code>true</code>, include Links as part of the results.
* Otherwise, set to <code>false</code>.
* @return a {@link Map} containing the information of the elements under
* the given folder.
* @throws DotHibernateException
* An error occurred during a Hibernate transaction.
* @throws DotSecurityException
* The current user does not have permission to perform this
* action.
* @throws DotDataException
* An error occurred when interacting with the database.
*/
public Map<String, Object> getFolderContent(String folderId, int offset,
int maxResults, String filter, List<String> mimeTypes,
List<String> extensions, boolean showArchived, boolean noFolders,
boolean onlyFiles, String sortBy, boolean sortByDesc,
boolean excludeLinks) throws DotSecurityException, DotDataException {
WebContext ctx = WebContextFactory.get();
HttpServletRequest req = ctx.getHttpServletRequest();
User usr = getUser(req);
long getAllLanguages = 0;
Map<String, Object> results = browserAPI.getFolderContent(usr,
folderId, offset, maxResults, filter, mimeTypes, extensions,
showArchived, noFolders, onlyFiles, sortBy, sortByDesc,
excludeLinks, getAllLanguages);
listCleanup((List<Map<String, Object>>) results.get("list"), getContentSelectedLanguageId(req));
return results;
}
/**
* The list of content under a folder might include the identifier
* several times, representing all the available languages for a single
* content.
* <p>
* This method takes that list and <i>leaves only one identifier per
* page</i>. This unique record represents either the content with the default
* language ID, or the content with the next language ID in the list of system
* languages.
* </p>
* * <p>
* If the fallback properties are false <i>leaves only one identifier per
* page that match the param languageId</i>.
* </p>
*
* @param results
* - The full list of pages under a given path/directory.
* @param languageId
* - Content Language of the results.
*/
private void listCleanup(List<Map<String, Object>> results, long languageId) {
Map<String, Integer> contentLangCounter = new HashMap<>();
// Examine only the pages with more than 1 assigned language
for (Map<String, Object> content : results) {
if ((boolean) content.get("isContentlet")) {
String ident = (String) content.get("identifier");
if (contentLangCounter.containsKey(ident)) {
int counter = contentLangCounter.get(ident);
contentLangCounter.put(ident, counter + 1);
} else {
contentLangCounter.put(ident, 1);
}
}
}
Set<String> identifierSet = contentLangCounter.keySet();
for (String identifier : identifierSet) {
int counter = contentLangCounter.get(identifier);
if (counter > 1) {
// Remove all languages except the default one
boolean isDeleted = removeAdditionalLanguages(identifier, results, languageId);
if (!isDeleted) {
// Otherwise, leave only the next available language
List<Language> languages = this.languageAPI.getLanguages();
for (Language language : languages) {
if (language.getId() != languageId) {
isDeleted = removeAdditionalLanguages(identifier, results, language.getId());
if (isDeleted) {
break;
}
}
}
}
}
}
}
/**
* Removes all other contents from the given list that ARE NOT associated to
* the specified language ID. In the end, the list will contain one content per
* identifier with either the default language ID or the next available
* language.
*
* @param identifier
* - The identifier of the page to clean up in the list.
* @param resultList
* - The list of all pages that will be displayed.
* @param languageId
* - The language ID of the page that will remain in the list.
* @return If <code>true</code>, the identifier with the specified language
* ID was successfully cleaned up. If <code>false</code>, the
* identifier is not associated to the specified language ID and was
* not removed from the list.
*/
private boolean removeAdditionalLanguages(String identifier,
List<Map<String, Object>> resultList, long languageId) {
boolean removeOtherLangs = false;
for (Map<String, Object> contentInfo : resultList) {
if ((boolean) contentInfo.get("isContentlet")) {
String ident = (String) contentInfo.get("identifier");
if (identifier.equals(ident)) {
long langId = (long) contentInfo.get("languageId");
// If specified language is found, remove all others
if (languageId == langId) {
removeOtherLangs = true;
break;
}
}
}
}
if (removeOtherLangs) {
removeLangOtherThan(resultList, identifier, languageId);
}
return removeOtherLangs;
}
/**
* Removes all the pages from the list that are not associated to the
* specified language. In the end, the list will contain one page per
* identifier.
*
* @param resultList
* - The list of pages that will be displayed.
* @param identifier
* - The identifier for the page to lookup in the list.
* @param languageId
* - The language ID that <b>MUST REMAIN</b> in the list.
*/
private void removeLangOtherThan(List<Map<String, Object>> resultList,
String identifier, long languageId) {
List<Integer> itemsToRemove = new ArrayList<Integer>();
for (int i = 0; i < resultList.size(); i++) {
Map<String, Object> pageInfo = resultList.get(i);
if ((boolean) pageInfo.get("isContentlet")) {
String ident = (String) pageInfo.get("identifier");
if (identifier.equals(ident)) {
long langId = (long) pageInfo.get("languageId");
if (languageId != langId) {
itemsToRemove.add(i);
}
}
}
}
int deletionCounter = 0;
for (int index : itemsToRemove) {
// Adjust index based on previous deletions
int indexAfterDeletion = index - deletionCounter;
resultList.remove(indexAfterDeletion);
deletionCounter++;
}
}
public Map<String, Object> saveFileAction(String selectedItem,String wfActionAssign,String wfActionId,String wfActionComments, String wfConId, String wfPublishDate,
String wfPublishTime, String wfExpireDate, String wfExpireTime, String wfNeverExpire, String whereToSend, String forcePush) throws DotSecurityException, ServletException{
WebContext ctx = WebContextFactory.get();
User user = getUser(ctx.getHttpServletRequest());
Contentlet contentlet = null;
Map<String, Object> result = new HashMap<String, Object>();
WorkflowAPI wapi = APILocator.getWorkflowAPI();
try {
WorkflowAction action = wapi.findAction(wfActionId, user);
if (action == null) {
throw new ServletException("No such workflow action");
}
contentlet = APILocator.getContentletAPI().find(wfConId, user, false);
contentlet.setStringProperty("wfActionId", action.getId());
contentlet.setStringProperty("wfActionComments", wfActionComments);
contentlet.setStringProperty("wfActionAssign", wfActionAssign);
contentlet.setStringProperty("wfPublishDate", wfPublishDate);
contentlet.setStringProperty("wfPublishTime", wfPublishTime);
contentlet.setStringProperty("wfExpireDate", wfExpireDate);
contentlet.setStringProperty("wfExpireTime", wfExpireTime);
contentlet.setStringProperty("wfNeverExpire", wfNeverExpire);
contentlet.setStringProperty("whereToSend", whereToSend);
contentlet.setStringProperty("forcePush", forcePush);
contentlet.setTags();
wapi.fireWorkflowNoCheckin(contentlet, user);
result.put("status", "success");
result.put("message", UtilMethods.escapeSingleQuotes(LanguageUtil.get(user, "Workflow-executed")));
} catch (Exception e) {
Logger.error(BrowserAjax.class, e.getMessage(), e);
result.put("status", "error");
try {
result.put("message",
UtilMethods.escapeSingleQuotes(LanguageUtil.get(user, "Workflow-action-execution-error")+" "+ e.getMessage()));
}catch(LanguageException le){
Logger.error(BrowserAjax.class, le.getMessage(), le);
}
}
return result;
}
public Map<String, Object> getFileInfo(String fileId, long languageId) throws DotDataException, DotSecurityException, PortalException, SystemException {
WebContext ctx = WebContextFactory.get();
HttpServletRequest req = ctx.getHttpServletRequest();
ServletContext servletContext = ctx.getServletContext();
User user = userAPI.getLoggedInUser(req);
boolean respectFrontendRoles = userAPI.isLoggedToFrontend(req);
Identifier ident = APILocator.getIdentifierAPI().find(fileId);
if(languageId==0) {
languageId = languageAPI.getDefaultLanguage().getId();
}
if(ident!=null && InodeUtils.isSet(ident.getId()) && ident.getAssetType().equals("contentlet")) {
ContentletVersionInfo vinfo=versionAPI.getContentletVersionInfo(ident.getId(), languageId);
if(vinfo==null && Config.getBooleanProperty("DEFAULT_FILE_TO_DEFAULT_LANGUAGE", false)) {
languageId = languageAPI.getDefaultLanguage().getId();
vinfo=versionAPI.getContentletVersionInfo(ident.getId(), languageId);
}
boolean live = respectFrontendRoles || vinfo.getLiveInode()!=null;
Contentlet cont = contentletAPI.findContentletByIdentifier(ident.getId(),live, languageId , user, respectFrontendRoles);
if(cont.getStructure().getStructureType()==Structure.STRUCTURE_TYPE_FILEASSET) {
FileAsset fileAsset = APILocator.getFileAssetAPI().fromContentlet(cont);
java.io.File file = fileAsset.getFileAsset();
String mimeType = servletContext.getMimeType(file.getName().toLowerCase());
Map<String, Object> fileMap = fileAsset.getMap();
fileMap.put("mimeType", mimeType);
fileMap.put("path", fileAsset.getPath());
fileMap.put("type", "contentlet");
return fileMap;
}
else if(cont.getStructure().getStructureType()==Structure.STRUCTURE_TYPE_HTMLPAGE) {
HTMLPageAsset page = APILocator.getHTMLPageAssetAPI().fromContentlet(cont);
Map<String, Object> pageMap = page.getMap();
pageMap.put("mimeType", "application/dotpage");
pageMap.put("pageURI", ident.getURI());
return pageMap;
}
}
return null;
}
@SuppressWarnings("unchecked")
private List<Map> getFoldersTree (Host host, Role[] roles) throws DotStateException, DotDataException, DotSecurityException {
FolderAPI folderAPI = APILocator.getFolderAPI();
List<Folder> children = new ArrayList<Folder>();
try {
children = folderAPI.findSubFolders(host,userAPI.getSystemUser(),false);
} catch (Exception e) {
Logger.error(this, "Could not load folders : ",e);
}
return getFoldersTree(host.getIdentifier(), children, roles);
}
@SuppressWarnings("unchecked")
private List<Map> getFoldersTree (Folder parent, Role[] roles) throws DotStateException, DotDataException, DotSecurityException {
FolderAPI folderAPI = APILocator.getFolderAPI();
List<Folder> children = new ArrayList<Folder>();
try {
children = folderAPI.findSubFolders(parent,userAPI.getSystemUser(),false);
} catch (Exception e) {
Logger.error(this, "Could not load folders : ",e);
}
return getFoldersTree(parent.getInode(), children, roles);
}
private List<Map> getFoldersTree (String parentInode, List<Folder> children, Role[] roles) throws DotStateException, DotDataException, DotSecurityException {
WebContext ctx = WebContextFactory.get();
User usr = getUser(ctx.getHttpServletRequest());
ArrayList<Map> folders = new ArrayList<Map> ();
for (Folder f : children) {
Map<String, Object> folderMap = f.getMap();
if (openFolders.contains(f.getInode())) {
List<Map> childrenMaps = getFoldersTree (f, roles);
folderMap.put("open", true);
folderMap.put("childrenFolders", childrenMaps);
} else {
folderMap.put("open", false);
}
if(f.getInode().equalsIgnoreCase(activeFolderInode))
folderMap.put("selected", true);
else
folderMap.put("selected", false);
folderMap.put("parent", parentInode);
List permissions = new ArrayList();
try {
permissions = permissionAPI.getPermissionIdsFromRoles(f, roles, usr);
} catch (DotDataException e) {
Logger.error(this, "Could not load permissions : ",e);
}
folderMap.put("permissions", permissions);
folders.add(folderMap);
}
return folders;
}
public Map<String, Object> renameFolder (String inode, String newName) throws DotDataException, DotSecurityException {
WebContext ctx = WebContextFactory.get();
User usr = getUser(ctx.getHttpServletRequest());
HashMap<String, Object> result = new HashMap<String, Object> ();
Folder folder = APILocator.getFolderAPI().find(inode, usr, false);
result.put("lastName", folder.getName());
result.put("extension", "");
result.put("newName", newName);
result.put("inode", folder.getInode());
result.put("assetType", "folder");
try {
if (folderAPI.renameFolder(folder, newName,usr,false)) {
result.put("result", 0);
} else {
result.put("result", 1);
result.put("errorReason", "There is another folder that has the same name");
}
} catch (Exception e) {
Logger.error(this, "Problem occured in the method renameFolder: ",e);
}
return result;
}
/**
* Copies a given inode folder/host reference into another given folder
*
* @param inode folder inode
* @param newFolder This could be the inode of a folder or a host
* @return Confirmation message
* @throws Exception
*/
public String copyFolder ( String inode, String newFolder ) throws Exception {
HttpServletRequest request = WebContextFactory.get().getHttpServletRequest();
User user = getUser( request );
UserWebAPI userWebAPI = WebAPILocator.getUserWebAPI();
HostAPI hostAPI = APILocator.getHostAPI();
final Locale requestLocale = request.getLocale();
final String successString = UtilMethods.escapeSingleQuotes(LanguageUtil.get(requestLocale, "Folder-copied"));
final String errorTryToMoveFolderToItself = UtilMethods.escapeSingleQuotes(LanguageUtil.get(requestLocale, "Folder-copied-to-itself"));
final String errorTryToMoveFolderToChild = UtilMethods.escapeSingleQuotes(LanguageUtil.get(requestLocale, "Folder-copied-to-children"));
//Searching for the folder to copy
Folder folder = APILocator.getFolderAPI().find( inode, user, false );
try {
if ( !folderAPI.exists( newFolder ) ) {
Host parentHost = hostAPI.find( newFolder, user, !userWebAPI.isLoggedToBackend( request ) );
if ( !permissionAPI.doesUserHavePermission( folder, PERMISSION_WRITE, user ) || !permissionAPI.doesUserHavePermission( parentHost, PERMISSION_WRITE, user ) ) {
throw new DotRuntimeException( "The user doesn't have the required permissions." );
}
folderAPI.copy( folder, parentHost, user, false );
refreshIndex( null, parentHost, folder );
} else {
Folder parentFolder = APILocator.getFolderAPI().find( newFolder, user, false );
if ( !permissionAPI.doesUserHavePermission( folder, PermissionAPI.PERMISSION_WRITE, user ) || !permissionAPI.doesUserHavePermission( parentFolder, PERMISSION_WRITE, user ) ) {
throw new DotRuntimeException( "The user doesn't have the required permissions." );
}
if ( parentFolder.getInode().equalsIgnoreCase( folder.getInode() ) ) {
//Trying to move a folder over itself
return errorTryToMoveFolderToItself;
}
if ( folderAPI.isChildFolder( parentFolder, folder ) ) {
//Trying to move a folder over one of its children
return errorTryToMoveFolderToChild;
}
folderAPI.copy( folder, parentFolder, user, false );
refreshIndex(parentFolder, null, folder );
}
} catch(InvalidFolderNameException e ) {
Logger.error(this, "Error copying folder with id:" + folder.getInode() + " into folder with id:"
+ newFolder + ". Error: " + e.getMessage());
return e.getLocalizedMessage();
}
return successString;
}
/**
* Moves a given inode folder/host reference into another given folder
*
* @param folderId folder identifier
* @param newFolderId This could be the inode of a folder or a host
* @return Confirmation message
* @throws Exception
*/
public String moveFolder (final String folderId, final String newFolderId) throws Exception {
final HttpServletRequest request = WebContextFactory.get().getHttpServletRequest();
final Locale requestLocale = request.getLocale();
final String successString = UtilMethods.escapeSingleQuotes(LanguageUtil.get(requestLocale, "Folder-moved"));
final String errorString = UtilMethods.escapeSingleQuotes(LanguageUtil.get(requestLocale, "Failed-to-move-another-folder-with-the-same-name-already-exists-in-the-destination"));
try {
final User user = getUser(request);
final boolean respectFrontendRoles = !this.userAPI.isLoggedToBackend(request);
if (!this.folderAPI.move(folderId, newFolderId, user, respectFrontendRoles)) {
return errorString;
}
} catch(InvalidFolderNameException e ) {
Logger.error(this, "Error moving folder with id:" + folderId + " into folder with id:"
+ newFolderId + ". Error: " + e.getMessage());
return e.getLocalizedMessage();
}catch (Exception e) {
Logger.error(this, "Error moving folder with id:" + folderId + " into folder with id:"
+ newFolderId + ". Error: " + e.getMessage(), e);
return e.getLocalizedMessage();
}
return successString;
}
public Map<String, Object> renameFile (String inode, String newName) throws Exception {
HashMap<String, Object> result = new HashMap<String, Object> ();
HibernateUtil.startTransaction();
try {
HttpServletRequest req = WebContextFactory.get().getHttpServletRequest();
User user = null;
try {
user = com.liferay.portal.util.PortalUtil.getUser(req);
} catch (Exception e) {
Logger.error(this, "Error trying to obtain the current liferay user from the request.", e);
throw new DotRuntimeException ("Error trying to obtain the current liferay user from the request.");
}
Identifier id = APILocator.getIdentifierAPI().findFromInode(inode);
if(id!=null && id.getAssetType().equals("contentlet")){
Contentlet cont = APILocator.getContentletAPI().find(inode, user, false);
String lName = (String) cont.get(FileAssetAPI.FILE_NAME_FIELD);
result.put("lastName", lName.substring(0, lName.lastIndexOf(".")));
result.put("extension", UtilMethods.getFileExtension(cont.getStringProperty(FileAssetAPI.FILE_NAME_FIELD)));
result.put("newName", newName);
result.put("inode", inode);
if(!cont.isLocked()){
try{
if(APILocator.getFileAssetAPI().renameFile(cont, newName, user, false)){
result.put("result", 0);
}else{
result.put("result", 1);
result.put("errorReason", "Another file with the same name already exists on this folder");
}
}catch(Exception e){
result.put("result", 1);
result.put("errorReason", e.getLocalizedMessage());
}
}else{
result.put("result", 1);
result.put("errorReason", "The file is locked");
}
}
} catch ( Exception e ) {
HibernateUtil.rollbackTransaction();
} finally {
HibernateUtil.closeAndCommitTransaction();
}
return result;
}
/**
* Copies a given inode reference to a given folder
*
* @param inode Contentlet inode
* @param newFolder This could be the inode of a folder or a host
* @return Confirmation message
* @throws Exception
*/
public Map<String, Object> copyFile ( String inode, String newFolder ) throws Exception {
HttpServletRequest req = WebContextFactory.get().getHttpServletRequest();
User user = getUser( req );
Map<String, Object> result = new HashMap<String, Object>();
try{
//Contentlet file identifier
Identifier id = APILocator.getIdentifierAPI().findFromInode( inode );
// gets folder parent
Folder parent = null;
try {
parent = APILocator.getFolderAPI().find( newFolder, user, false );
} catch ( Exception ignored ) {
//Probably what we have here is a host
}
Host host = null;
if ( parent == null ) {//If we didn't find a parent folder lets verify if this is a host
host = APILocator.getHostAPI().find( newFolder, user, false );
}
// Checking permissions
if(!hasFileWritePermissions(host, parent, id, user)) {
result.put("status", "error");
result.put("message", UtilMethods.escapeSingleQuotes(LanguageUtil.get(user, "File-failed-to-copy-check-you-have-the-required-permissions")));
return result;
}
if ( id != null && id.getAssetType().equals( "contentlet" ) ) {
//Getting the contentlet file
Contentlet cont = APILocator.getContentletAPI().find( inode, user, false );
if ( parent != null ) {
FileAsset fileAsset = APILocator.getFileAssetAPI().fromContentlet( cont );
if ( UtilMethods.isSet( fileAsset.getUnderlyingFileName() ) && !folderAPI.matchFilter( parent, fileAsset.getUnderlyingFileName() ) ) {
result.put("status", "error");
result.put("message", UtilMethods.escapeSingleQuotes(LanguageUtil.get(user, "message.file_asset.error.filename.filters")));
return result;
}
}
if ( parent != null ) {
APILocator.getContentletAPI().copyContentlet( cont, parent, user, false );
} else {
APILocator.getContentletAPI().copyContentlet( cont, host, user, false );
}
// issues/1788
// issues/1967
Folder srcFolder = APILocator.getFolderAPI().find(cont.getFolder(),user,false);
refreshIndex(parent, host, srcFolder );
result.put("status", "success");
result.put("message", UtilMethods.escapeSingleQuotes(LanguageUtil.get(user, "File-copied")));
return result;
}
return result;
}
catch(Exception ex) {
Logger.error(this, "Error trying to copy the file to folder.", ex);
// File asset URL already exist
if(ex instanceof DotDataException && ((DotDataException) ex).getMessage().equalsIgnoreCase("error.copy.url.conflict")) {
result.put("status", "error");
result.put("message", UtilMethods.escapeSingleQuotes(LanguageUtil.get(user, "message.htmlpage.error.htmlpage.exists.file")));
return result;
}
result.put("status", "error");
result.put("message", UtilMethods.escapeSingleQuotes(LanguageUtil.get(user, "message.file.error.generic.copy")));
return result;
}
}
/**
* This method verify if the user has write permissions of the file asset
* @param host
* @param parent
* @param id
* @param user
* @return true if has permissions otherwise false
*/
private boolean hasFileWritePermissions(Host host, Folder parent, Identifier id, User user) {
boolean allowed = false;
final String permissionsError = "The user doesn't have the required permissions.";
try {
// Checking permissions
if ( !permissionAPI.doesUserHavePermission( id, PERMISSION_WRITE, user ) ) {
Logger.error(this, permissionsError);
} else if ( parent != null && !permissionAPI.doesUserHavePermission( parent, PERMISSION_WRITE, user ) ) {
Logger.error(this, permissionsError);
} else if ( host != null && !permissionAPI.doesUserHavePermission( host, PERMISSION_WRITE, user ) ) {
Logger.error(this, permissionsError);
} else {
allowed = true;
}
} catch(DotDataException e) {
Logger.error(this, permissionsError, e);
}
return allowed;
}
/**
* Moves a given inode reference to a given folder
*
* @param inode Contentlet inode
* @param folder This could be the inode of a folder or a host
* @return true if success, false otherwise
* @throws Exception