-
Notifications
You must be signed in to change notification settings - Fork 0
/
generateIA.js
1659 lines (1465 loc) · 67.9 KB
/
generateIA.js
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
var spLibraries = ["Documents","Form Templates","List Template Gallery","Master Page Gallery","Site Assets","Site Pages","Solution Gallery","Style Library","Theme Gallery","Web Part Gallery","wfpub","fpdatasources","wfsvc","Converted Forms"]
var spFields = ["Approval Status"];
var spRoles = ["Limited Access"];
var spFolders = ["Forms","_w","_t"];
var spInternalNames = {"Series_x0020_Corporate_x0020_IDB":"Series", "Function_x0020_Corporate_x0020_IDB":"Function", "Project_x0020_Number":"Project Number", "System_x0020_Name":"System Name", "Function Corporate IDB":"Function", "Series Corporate IDB":"Series", "Document_x0020_Author":"Document Author","Function_x0020_Operations_x0020_IDB":"Function","Series_x0020_Operations_x0020_IDB":"Series","Approval_x0020_Number":"Approval Number","Sector_x0020_IDB":"Sector IDB","_dlc_DocIdUrl":"Document ID","Fiscal_x0020_Year_x0020_IDB":"Fiscal Year","TaxKeyword":"Tags","IDBDocs_x0020_Number":"IDBDocs Number","Editor":"Modified By","Division_x0020_or_x0020_Unit":"Division or Unit","Document_x0020_Language_x0020_IDB":"Document Language"};
var spPropertyBags = ["IDBProjectNumber","IDBSiteName","IDBSector","IDBFund","IDBSiteCoordinator","IDBProjectName","IDBOrgUnit","IDBOperationType","IDBOrganizationalFunction","IDBCountry","IDBSiteType","IDBCreatedOn","IDBCreatedby","IDBSiteDescription","IDBSubSector"];
var spViews = ['Merge Documents','Relink Documents','assetLibTemp'];
var ordinals = ["First","Second","Third","Fourth","Fifth","Sixth","Seventh","Eight"];
var ezDefaults = ["Disclosed","IIC"];
var ezPermissions = {"Contribute":2, "Full Control":4, "Read":1, "Design":3, "View Only":1, "Edit":2};
var listDefaults = [];
var listMembers = [];
var specialNames = {};
var structure = {};
var defaultsStructure = {};
var queue = [];
var queueFolders = [];
var queueLibraries = [];
var queueLibrariesDefaults = [];
var queueSecurity = [];
var SubsiteDepth = 1;
var ContentTypeDepth = 1;
var defaultsDepth = 1;
var securityDepth = 1;
var foldersDepth = 0;
var getMetadata = true;
var getStructure = true;
var getSecurity = true;
var getContentTypes = true;
var getDefaults = true;
var getViews = true;
var viewsCount = 0;
var columnsCount = 0;
var tableToExcel = (function () {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }
return function (table, name, wbname) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
var link = document.createElement("A");
link.href = uri + base64(format(template, ctx));
link.download = wbname || 'Workbook.xls';
link.target = '_blank';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
})();
$(function() {
$(".ms-rte-layoutszone-outer").hide();
$("#sideNavBox").hide();
$("#DeltaTopNavigation").hide();
$("#searchInputBox").hide();
$("#pageTitle").find('a').text("Information Architecture Generator");
$("#pageTitle").css("margin-top","20px");
$("#contentBox").css("margin-left","20px");
$("#contentBox").append('<div id="IAinfo" style="margin:0px auto;width:480px;overflow:none;"></div>');
$("#IAinfo").append('<input type="text" placeholder="Enter the Site url" id="getStructureSite" style="width:300px;padding:6px;height:26px;"/>');
$("#IAinfo").append('<input type="button" id="getStructure" value="Generate" style="margin-left:-4px;padding:7px 58px;background:#12888a;height:40px;border: none;color: white;font-size: 13px;cursor:pointer;"/>');
$("#IAinfo").append('<div id="generatorSettings" style="display:none;margin-top:10px;padding-bottom:10px;border-bottom:1px solid #bdbdbd;"><label><input type="checkbox" id="generateStructure" checked>Site Structure</label> <label><input type="checkbox" id="generateSecurity" checked>Security</label> <label><input type="checkbox" id="generateContentTypes" checked>Content Types</label> <label><input type="checkbox" id="generateDefaults" checked>Defaults</label><br><label><input type="checkbox" id="generateMetadata" checked>Site Metadata</label> <label><input type="checkbox" id="generateViews" checked>Library Views</label></div>');
$("#IAinfo").append('<div id="generatorSettingsLink" style="margin-top:5px;float:right;cursor:pointer;color:#0072c6;padding-right:5px;">Settings</div>');
$("#IAinfo").append('<div id="progressMessages" style="margin-top:5px;margin-bottom:20px;max-width:420px;overflow-x:hidden"></div>');
$("#contentBox").append('<div id="InfoOptions" style="display:none;margin-top:110px;margin-left:1px;"><div class="tabInfo active" id="showSiteStructure">Site Structure and Security</div><div class="tabInfo" style="float:left" id="showBagProperties">Site metadata</div><div class="tabInfo" style="float:left;display:none;" id="showViews">Views</div><a id="exportExcel" unselectable="on" class="ms-cui-ctl-medium " mscui:controltype="Button" role="button"><span unselectable="on" class="ms-cui-ctl-iconContainer"><span unselectable="on" class=" ms-cui-img-16by16 ms-cui-img-cont-float"><img unselectable="on" alt="" src="/_layouts/15/1033/images/formatmap16x16.png?rev=43" style="top: -243px; left: -55px;"></span></span><span unselectable="on" class="ms-cui-ctl-mediumlabel">Export to Excel</span></a><div style="clear:both;"></div></div>');
$("#contentBox").append('<div id="displayResults" style="margin-top:0px;"></div>');
$("#exportExcel").click(function() {
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var user = web.get_currentUser(); //must load this to access info.
context.load(user);
context.executeQueryAsync(function(){
$(".currentRequester").text(" " + user.get_title());
tableToExcel('siteStructure', 'Site Structure and Security', new Date().toISOString().slice(0, 10) + '_IA' + "_" + structure['Title']);
if(getMetadata)
tableToExcel('bagProperties', 'Bag Properties', structure['Title'] + '_Bag Properties');
}, function(){console.log("Error getting current user");});
});
$("#generatorSettingsLink").click(function() {
$("#generatorSettings").toggle();
});
$("#showSiteStructure").click(function() {
$("#showSiteStructure").addClass("active");
$("#showBagProperties").removeClass("active");
$("#showViews").removeClass("active");
$("#bagProperties").hide();
$(".libraryViews").hide();
$("#siteStructure").show();
});
$("#showBagProperties").click(function() {
$("#showSiteStructure").removeClass("active");
$("#showViews").removeClass("active");
$("#showBagProperties").addClass("active");
$("#bagProperties").show();
$("#siteStructure").hide();
$(".libraryViews").hide();
});
$("#showViews").click(function() {
$("#showSiteStructure").removeClass("active");
$("#showBagProperties").removeClass("active");
$("#showViews").addClass("active");
$("#bagProperties").hide();
$("#siteStructure").hide();
$(".libraryViews").show();
});
$('body').keypress(function (e) {
if (e.which == 13) {
if($("#getStructureSite").val()!="")
$('#getStructure').click();
return false;
}
});
$("#generateContentTypes").click( function(){
if($(this).is(':checked')) {
$('#generateStructure').prop('checked',true);
}
});
$("#generateSecurity").click( function(){
if($(this).is(':checked')) {
$('#generateStructure').prop('checked',true);
}
});
$("#generateDefaults").click( function(){
if($(this).is(':checked')) {
$('#generateStructure').prop('checked',true);
}
});
$("#generateStructure").click( function(){
if(!$(this).is(':checked')) {
$('#generateSecurity').prop('checked',false);
$("#generateContentTypes").prop('checked',false);
$("#generateDefaults").prop('checked',false);
}
});
$("#getStructureSite").click(function() {
$(this).select();
});
$("#getStructure").click(function() {
if($("#getStructureSite").val()=="")
alert("Enter the site URL");
else{
$("#InfoOptions").hide();
$("#displayResults").html("");
structure = {};
defaultsStructure = {};
structure['url'] = $("#getStructureSite").val();
structure['libraries'] = {};
queue = [];
queueLibraries = [];
queueFolders = [];
specialNames = {};
queueLibrariesDefaults = [];
queueSecurity = [];
listDefaults = [];
listMembers = [];
SubsiteDepth = 1;
ContentTypeDepth = 1;
defaultsDepth = 1;
securityDepth = 1;
foldersDepth = 0;
getMetadata = true;
getStructure = true;
getSecurity = true;
getContentTypes = true;
getDefaults = true;
getViews = true;
if(!$('#generateMetadata').is(':checked'))
getMetadata = false;
if(!$('#generateStructure').is(':checked'))
getStructure = false;
if(!$('#generateSecurity').is(':checked'))
getSecurity = false;
if(!$('#generateContentTypes').is(':checked'))
getContentTypes = false;
if(!$("#generateDefaults").is(':checked'))
getDefaults = false;
if(!$('#generateStructure').is(':checked'))
getStructure = false;
if(!$('#generateViews').is(':checked'))
getViews = false;
queue.push({'url':structure['url'],'structure':structure['libraries']});
$("#getStructureSite").prop('disabled', true);
$("#getStructure").prop('disabled', true);
$("#displayResults").append("<div style='width:390px;margin:200px auto;'><img src='/teams/ITE/Office365/eZShare/SiteAssets/hex-loader2.gif'></div>");
//$("#gettingStructure").attr('src',"/teams/ITE/Office365/eZShare/SiteAssets/21.gif");
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){
getAllWebs(
function(allwebs){
structure['subsites'] = {};
for (var key in allwebs){
var levels = allwebs[key]['structure'].split(";");
if(SubsiteDepth<Math.ceil(levels.length/2))
SubsiteDepth = Math.ceil(levels.length/2);
var aux = structure;
for (var j = 1; j < (levels.length); j++){
if(j % 2 != 0){
if('subsites' in aux){
aux = aux["subsites"];
}else{
aux['subsites'] = {};
aux = aux['subsites'];
}
}else{
if(levels[j] in aux){
aux = aux[levels[j]];
}else{
aux[levels[j]] = {};
aux = aux[levels[j]];
}
}
}
aux['url'] = allwebs[key]['url'];
if(getStructure){
aux['libraries'] = {};
if(getSecurity){
aux['Permissions'] = {};
for(member in allwebs[key]["Permissions"]){
aux['Permissions'][member] = allwebs[key]["Permissions"][member];
}
}
queue.push({'url':allwebs[key]['url'],'structure':aux['libraries']});
}
if(getMetadata){
aux['bagProperties'] = {};
for(var prop in allwebs[key]['bagProperties']){
aux['bagProperties'][prop] = allwebs[key]['bagProperties'][prop];
}
}
}
if(getStructure || getViews){
$("#progressMessages").html("").append("<img src='/teams/ITE/Office365/eZShare/SiteAssets/loading.gif'/> Retrieving Libraries");
retrieveAllLibraries();
}else{
retrieveRootProperties();
}
},
function(sendera,args){
alert(args.get_message());
console.log("root failed");
$("#getStructure").prop('disabled', false);
$("#getStructureSite").prop('disabled', false);
$("#displayResults").html("");
$("#progressMessages").html("");
});
});
}
});
function getAllWebs(success,error){
$("#progressMessages").html("").append("<img src='/teams/ITE/Office365/eZShare/SiteAssets/loading.gif'/> Retrieving subsites");
var ctx = new SP.ClientContext(structure['url']);
var web = ctx.get_web();
var result = {};
var level = 0;
var initial = "root";
var getAllWebsInner = function(web,result,success,error,initial)
{
level++;
var ctx = web.get_context();
var webs = web.getSubwebsForCurrentUser(null);
ctx.load(webs,'Include(Title,Webs,Url,AllProperties,RoleAssignments.Include(Member,RoleDefinitionBindings))');
//ctx.load(webs, site => site.Include(Title,Webs,Url,AllProperties));
ctx.executeQueryAsync(
function(){
for(var i = 0; i < webs.get_count();i++){
var web = webs.getItemAtIndex(i);
// Changing the Message
$("#progressMessages").html("").append("<img src='/teams/ITE/Office365/eZShare/SiteAssets/loading.gif'/> " + web.get_title() + " - found");
result[web.get_title()] = {};
result[web.get_title()]['web'] = web;
result[web.get_title()]['structure'] = initial + ";#S#;" +web.get_title();
result[web.get_title()]['url'] = web.get_url();
if(getMetadata){
var allProps = web.get_allProperties().get_fieldValues();
result[web.get_title()]['bagProperties'] = {}
for (var prop in allProps) {
if(prop.startsWith('IDB')){
result[web.get_title()]['bagProperties'][prop] = allProps[prop];
}
}
}
if(getSecurity){
var permissionsEnumerator = web.get_roleAssignments().getEnumerator();
var permissions = {};
while (permissionsEnumerator.moveNext()) {
var permission = permissionsEnumerator.get_current();
var rolesEnumerator = permission.get_roleDefinitionBindings().getEnumerator();
while (rolesEnumerator.moveNext()) {
var role = rolesEnumerator.get_current();
if(spRoles.indexOf(role.get_name())==-1){
permissions[permission.get_member().get_title()] = role.get_name();
if($.inArray(permission.get_member().get_title(), listMembers) == -1)
listMembers.push(permission.get_member().get_title());
}
}
}
result[web.get_title()]['Permissions'] = {}
for(var permission in permissions){
result[web.get_title()]['Permissions'][permission] = permissions[permission];
}
}
if(web.get_webs().get_count() > 0) {
getAllWebsInner(web,result,success,error,initial + ";#S#;" +web.get_title());
}
}
level--;
if (level == 0 && success){
success(result);
}
},
error);
};
getAllWebsInner(web,result,success,error);
}
function retrieveAllLibraries() {
if(queue.length > 0){
var actualSite = queue.pop();
var ctx = new SP.ClientContext(actualSite['url']);
web = ctx.get_web();
lists = web.get_lists();
//ctx.load(lists,'Include(Title,BaseType,Fields.Include(Title,InternalName,DefaultValue,TypeAsString),ContentTypes.Include(Name),RootFolder,RoleAssignments.Include(Member,RoleDefinitionBindings))');
ctx.load(lists, 'Include(Title,BaseType,ContentTypes.Include(Name), Fields.Include(Title,InternalName,DefaultValue,TypeAsString), Views.Include(Title,ViewFields,DefaultView,Aggregations,RowLimit,ViewQuery))');
ctx.executeQueryAsync(function(){onQuerySucceeded(actualSite['structure'],actualSite['url'])}, onQueryFailed);
}else{
if(getStructure){
/*
for(var i=0;i<queueLibraries.length;i++){
console.log(queueLibraries[i]);
}
*/
retrieveAllLibrariesInfo();
}else{
retrieveRootProperties();
}
}
}
function onQuerySucceeded(librariesStructure, url, sender, args) {
var listEnumerator = lists.getEnumerator();
while (listEnumerator.moveNext()) {
var currentContentTypesDepth = 0;
var oList = listEnumerator.get_current();
if(oList.get_baseType() == 1){
if(spLibraries.indexOf(oList.get_title())==-1){
// Creating the Library in the general structure
librariesStructure[oList.get_title()] = {}
// Getting the Views
librariesStructure[oList.get_title()]['views'] = {};
var viewsEnumerator = oList.get_views().getEnumerator();
var count = 0;
while (viewsEnumerator.moveNext()){
var view = viewsEnumerator.get_current();
if(spViews.indexOf(view.get_title())==-1){
librariesStructure[oList.get_title()]['views'][view.get_title()] = {};
librariesStructure[oList.get_title()]['views'][view.get_title()]["default"] = view.get_defaultView();
var totals = "";
var xmlDoc = new DOMParser().parseFromString(view.get_aggregations(), 'text/xml');
var items = xmlDoc.getElementsByTagName('FieldRef');
for(var i = 0; i < items.length; i++) {
if(totals != ""){
totals += ";";
}
if(items[i].getAttribute('Name') in spInternalNames){
totals += spInternalNames[items[i].getAttribute('Name')] + " - " + items[i].getAttribute('Type');
}else{
totals += items[i].getAttribute('Name') + " - " + items[i].getAttribute('Type');
}
}
librariesStructure[oList.get_title()]['views'][view.get_title()]["totals"] = totals;
librariesStructure[oList.get_title()]['views'][view.get_title()]["limit"] = view.get_rowLimit();
var sort = "";
xmlDoc = new DOMParser().parseFromString("<document>" + view.get_viewQuery() + "</document>", 'text/xml');
items = xmlDoc.getElementsByTagName('OrderBy');
var order = "";
for(var i = 0; i < items.length; i++) {
var childitems = items[i].childNodes;
for(var j=0; j < childitems.length; j++){
if(sort != ""){
sort += ";";
}
if(childitems[j].getAttribute('Ascending')=="TRUE")
order = 'Ascending';
else
order = 'Descending';
if(childitems[j].getAttribute('Name') in spInternalNames){
sort += spInternalNames[childitems[j].getAttribute('Name')] + " - " + order;
}else{
sort += childitems[j].getAttribute('Name') + " - " + order;
}
}
}
librariesStructure[oList.get_title()]['views'][view.get_title()]["sort"] = sort;
items = xmlDoc.getElementsByTagName('GroupBy');
var group = "";
for(var i = 0; i < items.length; i++) {
var childitems = items[i].childNodes;
for(var j=0; j < childitems.length; j++){
if(group != ""){
group += ";";
}
if(childitems[j].getAttribute('Ascending')=="TRUE")
order = 'Ascending';
else
order = 'Descending';
if(childitems[j].getAttribute('Name') in spInternalNames){
group += "Column '" + spInternalNames[childitems[j].getAttribute('Name')] + "' - show groups in " + order + " order";
}else{
group += "Column '" + childitems[j].getAttribute('Name') + "' - show groups in " + order + " order";
}
}
}
librariesStructure[oList.get_title()]['views'][view.get_title()]["group"] = group;
items = xmlDoc.getElementsByTagName('Where');
var filter = "";
var operator = "";
for(var i = 0; i < items.length; i++){
if(filter != ""){
filter += ";";
}
var childitems = items[i].childNodes;
for(var j=0; j < childitems.length; j++){
if(childitems[j].nodeName=="Or" || childitems[j].nodeName=="And"){
if(childitems[j].childNodes[0].nodeName=="Eq"){
operator = "=";
filter += childitems[j].childNodes[0].childNodes[0].getAttribute('Name') + " " + operator + " ";
if(childitems[j].childNodes[0].childNodes[1].getAttribute('Type')=="Boolean")
if(childitems[j].childNodes[0].childNodes[1].childNodes[0].nodeValue == "1")
filter += "True";
else
filter += "False";
else
filter += childitems[j].childNodes[0].childNodes[1].childNodes[0].nodeValue;
}
filter += " " + childitems[j].nodeName + " ";
if(childitems[j].childNodes[1].nodeName=="Eq"){
operator = "=";
filter += childitems[j].childNodes[1].childNodes[0].getAttribute('Name') + " " + operator + " ";
if(childitems[j].childNodes[1].childNodes[1].getAttribute('Type')=="Boolean")
if(childitems[j].childNodes[1].childNodes[1].childNodes[0].nodeValue == "1")
filter += "True";
else
filter += "False";
else
filter += childitems[j].childNodes[1].childNodes[1].childNodes[0].nodeValue;
}
}else{
if(childitems[j].nodeName=="Eq"){
if(childitems[j].childNodes[0].getAttribute('Name')=="Author"){
if(childitems[j].childNodes[1].childNodes[0].nodeName=="UserID"){
filter += "'Created By' is equal to [Me]";
}
}
}
}
}
}
librariesStructure[oList.get_title()]['views'][view.get_title()]["filter"] = filter;
var fieldsEnumerator = view.get_viewFields().getEnumerator();
var fields = [];
while (fieldsEnumerator.moveNext()){
var field = fieldsEnumerator.get_current();
if(field in spInternalNames)
fields.push(spInternalNames[field]);
else
fields.push(field);
}
librariesStructure[oList.get_title()]['views'][view.get_title()]["columns"] = fields;
if(columnsCount < fields.length)
columnsCount = fields.length;
count++;
}
}
if(viewsCount < count){
viewsCount = count;
}
if(getStructure){
// Pushing the library to get the Defaults and Permissions later
queueLibraries.push({'name':oList.get_title(),'structure':librariesStructure[oList.get_title()],"url":url});
queueLibrariesDefaults.push({'name':oList.get_title(),'structure':librariesStructure[oList.get_title()],"url":url});
if(getContentTypes){
// Changing the Message
$("#progressMessages").html("").append("<img src='/teams/ITE/Office365/eZShare/SiteAssets/loading.gif'/> " + oList.get_title() + " - Retrieving Content Types");
// Getting the content types of the library
var contentTypes = [];
var contentTypesEnumerator = (oList.get_contentTypes()).getEnumerator();
while (contentTypesEnumerator.moveNext()) {
var contentType = contentTypesEnumerator.get_current();
if(contentType.get_name()!="Folder"){
currentContentTypesDepth++;
contentTypes.push(contentType.get_name());
}
}
if(currentContentTypesDepth>ContentTypeDepth)
ContentTypeDepth = currentContentTypesDepth;
// Setting the Content types to the library in the general structure
librariesStructure[oList.get_title()]['contentTypes'] = contentTypes;
}
if(getDefaults){
// Getting the default values of the library
var defaults = {};
var fieldEnumerator = (oList.get_fields()).getEnumerator();
while (fieldEnumerator.moveNext()) {
var field = fieldEnumerator.get_current();
if(spFields.indexOf(field.get_title())==-1){
if(field.get_defaultValue()!=null & field.get_defaultValue()!=""){
if($.inArray(field.get_title(), ezDefaults) == -1){
if(field.get_typeAsString() == "Boolean"){
if(field.get_defaultValue()==0)
defaults[field.get_title()] = false;
else
defaults[field.get_title()] = true;
}else{
var value = field.get_defaultValue();
if(value.indexOf(";#")!=-1){
value = value.split(";#")[1].split("|")[0];
}
defaults[field.get_title()] = value;
}
}
if(field.get_title() in spInternalNames){
if($.inArray(spInternalNames[field.get_title()], ezDefaults) == -1){
if($.inArray(spInternalNames[field.get_title()], listDefaults) == -1){
listDefaults.push(spInternalNames[field.get_title()]);
}
}
}else{
if($.inArray(field.get_title(), ezDefaults) == -1){
if($.inArray(field.get_title(), listDefaults) == -1){
listDefaults.push(field.get_title());
}
}
}
}
}
}
// Setting the Default Values to the library in the general structure
librariesStructure[oList.get_title()]['defaults'] = defaults;
}
}
}
}
}
retrieveAllLibraries();
}
function onQueryFailed(sender, args) {
/*alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());*/
console.log("error retrieveAllLibraries");
retrieveAllLibraries();
}
function retrieveAllLibrariesInfo(){
if(queueLibraries.length > 0){
var actualLibrary = queueLibraries.pop();
var ctx = new SP.ClientContext(actualLibrary['url']);
web = ctx.get_web();
list = web.get_lists().getByTitle(actualLibrary['name']);
//ctx.load(list,'RootFolder.Folders.Include(Name,ServerRelativeUrl,Folders,ListItemAllFields.RoleAssignments.Include(Member,RoleDefinitionBindings))');
ctx.load(list,'RootFolder.Folders.Include(Name,ServerRelativeUrl,Folders)');
ctx.load(list,'RootFolder.ServerRelativeUrl');
//ctx.load(list,'RoleAssignments.Include(Member,RoleDefinitionBindings)');
ctx.executeQueryAsync(function(){onQuerySucceededRetrieveAllLibrariesInfo(actualLibrary['structure'],actualLibrary['url'],actualLibrary['name'])}, onQueryFailedRetrieveAllLibrariesInfo);
}else{
retrieveFolders();
//retrieveAllDefaults();
}
}
function onQuerySucceededRetrieveAllLibrariesInfo(librariesStructure, url, name, sender, args) {
$("#progressMessages").html("").append("<img src='/teams/ITE/Office365/eZShare/SiteAssets/loading.gif'/> " + name + " - Retrieving Folders");
// Getting Folders
var foldersEnumerator = list.get_rootFolder().get_folders().getEnumerator();
var Folders = {};
librariesStructure['Folders'] = {};
librariesStructure['Permissions'] = {};
queueSecurity.push({'structure':librariesStructure['Permissions'],'url':url,'name':name,'type':'Library'});
while (foldersEnumerator.moveNext()) {
if(foldersDepth < 1)
foldersDepth = 1;
var folder = foldersEnumerator.get_current();
if(spFolders.indexOf(folder.get_name())==-1){
librariesStructure['Folders'][folder.get_name()] = {};
librariesStructure['Folders'][folder.get_name()]['url'] = location.protocol + '//' + location.hostname + folder.get_serverRelativeUrl();
librariesStructure['Folders'][folder.get_name()]['defaults'] = {};
librariesStructure['Folders'][folder.get_name()]['Permissions'] = {};
defaultsStructure[librariesStructure['Folders'][folder.get_name()]['url']] = librariesStructure['Folders'][folder.get_name()]['defaults'];
queueSecurity.push({'structure':librariesStructure['Folders'][folder.get_name()]['Permissions'],'url':url,'name':librariesStructure['Folders'][folder.get_name()]['url'],'type':'Folder'});
var subFoldersEnumerator = folder.get_folders().getEnumerator();
librariesStructure['Folders'][folder.get_name()]['Folders'] = {};
while (subFoldersEnumerator.moveNext()) {
var subFolder = subFoldersEnumerator.get_current();
librariesStructure['Folders'][folder.get_name()]['Folders'][subFolder.get_name()] = {};
queueFolders.push({'name':subFolder.get_name(),'structure': librariesStructure['Folders'][folder.get_name()]['Folders'][subFolder.get_name()],"url":url,"parent":name + "/" + folder.get_name(),"level":2});
}
}
}
librariesStructure['url'] = location.protocol + '//' + location.hostname + list.get_rootFolder().get_serverRelativeUrl();
if(!("defaults" in librariesStructure)){
librariesStructure['defaults'] = {};
}
defaultsStructure[librariesStructure['url']] = librariesStructure['defaults'];
retrieveAllLibrariesInfo();
}
function onQueryFailedRetrieveAllLibrariesInfo(sender, args) {
/*
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
*/
console.log("error onQueryFailedRetrieveAllLibrariesInfo");
retrieveAllLibrariesInfo();
}
function retrieveFolders(){
if(queueFolders.length > 0){
var actualFolder = queueFolders.pop();
var ctx = new SP.ClientContext(actualFolder['url']);
web = ctx.get_web();
folder = web.getFolderByServerRelativeUrl(encodeURI(actualFolder['url'] + '/' + actualFolder['parent'] + '/' + actualFolder['name']));
ctx.load(folder,'Name','ServerRelativeUrl','Folders');
ctx.executeQueryAsync(function(){onQuerySucceededRetrieveFolders(actualFolder['structure'],actualFolder['url'],actualFolder['name'],actualFolder['parent'] + '/' + actualFolder['name'],actualFolder['level'])}, onQueryFailedRetrieveFolders);
}else{
retrieveAllDefaults();
}
}
function onQuerySucceededRetrieveFolders(librariesStructure, url, name, parent, level, sender, args) {
if(foldersDepth < level)
foldersDepth = level;
var subFoldersEnumerator = folder.get_folders().getEnumerator();
librariesStructure['url'] = location.protocol + '//' + location.hostname + folder.get_serverRelativeUrl();
librariesStructure['Folders'] = {};
librariesStructure['defaults'] = {};
librariesStructure['Permissions'] = {};
defaultsStructure[librariesStructure['url']] = librariesStructure['defaults'];
queueSecurity.push({'structure':librariesStructure['Permissions'],'url':url,'name':librariesStructure['url'],'type':'Folder'});
while (subFoldersEnumerator.moveNext()) {
var subFolder = subFoldersEnumerator.get_current();
librariesStructure['Folders'][subFolder.get_name()] = {};
queueFolders.push({'name':subFolder.get_name(),'structure': librariesStructure['Folders'][subFolder.get_name()],"url":url,"parent":parent,"level": level + 1});
}
retrieveFolders();
}
function onQueryFailedRetrieveFolders(sender, args) {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
console.log("error onQueryFailedRetrieveAllFolders");
retrieveFolders();
}
function retrieveAllDefaults(){
if(getDefaults){
var actualLibrary = queueLibrariesDefaults.pop();
//console.log(actualLibrary);
if(typeof actualLibrary === "undefined"){
if(queueLibrariesDefaults.length > 0){
retrieveAllDefaults();
}else{
retrieveRootProperties();
}
}else{
$("#progressMessages").html("").append("<img src='/teams/ITE/Office365/eZShare/SiteAssets/loading.gif'/> " + actualLibrary['name'] + " - Retrieving Default Values");
var auxName = actualLibrary['name'].replace(/,/g,"").replace(/\(/g,"").replace(/\)/g,"").replace(/-/g,"");
specialNames[auxName] = actualLibrary['name'];
$.ajax({
url: actualLibrary['url'] + '/' + encodeURI(auxName) + '/Forms/client_LocationBasedDefaults.html',
retry: 3,
dataType: 'xml',
success: function (data){
$(data).find("a").each(function(){
var urlAux = location.protocol + '//' + location.hostname + decodeURIComponent($(this).attr("href"));
if(urlAux in defaultsStructure){
$(this).find("DefaultValue").each(function(){
var value = $(this).text();
if(value.indexOf(";#")!=-1){
value = value.split(";#")[1].split("|")[0];
}
if($(this).attr("FieldName") in spInternalNames){
if($.inArray(spInternalNames[$(this).attr("FieldName")], ezDefaults) == -1){
defaultsStructure[urlAux][spInternalNames[$(this).attr("FieldName")]] = value;
if($.inArray(spInternalNames[$(this).attr("FieldName")], listDefaults) == -1){
listDefaults.push(spInternalNames[$(this).attr("FieldName")]);
}
}
}else{
if($.inArray($(this).attr("FieldName"), ezDefaults) == -1){
defaultsStructure[urlAux][$(this).attr("FieldName")] = value;
if($.inArray($(this).attr("FieldName"), listDefaults) == -1){
listDefaults.push($(this).attr("FieldName"));
}
}
}
});
}
});
if(queueLibrariesDefaults.length > 0){
retrieveAllDefaults();
}else{
getSecurityElement();
}
},
error: function(xhr, errorThrown ) {
this.retry = this.retry - 1;
if(this.retry > 0){
if(this.retry > 1){
this.url = actualLibrary['url'] + '/' + encodeURI(actualLibrary['name']) + '/Forms/client_LocationBasedDefaults.html';
$.ajax(this);
}else{
var secondAux = auxName.replace(/\./g,"");
//console.log(secondAux);
this.url = actualLibrary['url'] + '/' + encodeURI(secondAux) + '/Forms/client_LocationBasedDefaults.html';
$.ajax(this);
}
}
else
retrieveAllDefaults();
return;
}
});
}
}else{
getSecurityElement();
}
}
function getSecurityElement(){
if(getSecurity){
if(queueSecurity.length > 0){
var actualLibrary = queueSecurity.pop();
var ctx = new SP.ClientContext(actualLibrary['url']);
web = ctx.get_web();
if(actualLibrary['type']=="Library"){
list = web.get_lists().getByTitle(actualLibrary['name']);
ctx.load(list,'RoleAssignments.Include(Member,RoleDefinitionBindings)');
}else{
list = web.getFolderByServerRelativeUrl(actualLibrary['name']);
ctx.load(list,'ListItemAllFields.RoleAssignments.Include(Member,RoleDefinitionBindings)');
}
ctx.executeQueryAsync(function(){onQuerySucceededGetSecurity(actualLibrary['structure'],actualLibrary['url'],actualLibrary['name'],actualLibrary['type'])}, onQueryFailedGetSecurity);
}else{
retrieveRootProperties();
}
}else{
retrieveRootProperties();
}
}
function onQuerySucceededGetSecurity(librariesStructure, url, name, type, sender, args) {
if(getSecurity){
$("#progressMessages").html("").append("<img src='/teams/ITE/Office365/eZShare/SiteAssets/loading.gif'/> " + name + " - Retrieving Permissions");
// Getting the permissions
if(type=="Library")
var permissionsEnumerator = list.get_roleAssignments().getEnumerator();
else
var permissionsEnumerator = list.get_listItemAllFields().get_roleAssignments().getEnumerator();
while (permissionsEnumerator.moveNext()) {
var permission = permissionsEnumerator.get_current();
var rolesEnumerator = permission.get_roleDefinitionBindings().getEnumerator();
while (rolesEnumerator.moveNext()) {
var role = rolesEnumerator.get_current();
if(spRoles.indexOf(role.get_name())==-1){
librariesStructure[permission.get_member().get_title()] = role.get_name();
if($.inArray(permission.get_member().get_title(), listMembers) == -1)
listMembers.push(permission.get_member().get_title());
}
}
}
}
getSecurityElement();
}
function onQueryFailedGetSecurity(sender, args) {
/*
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
*/
console.log("error onQueryFailedGetSecurity: " + args.get_message() + '\n' + args.get_stackTrace());
getSecurityElement();
}
function retrieveRootProperties(){
var ctx = new SP.ClientContext(structure['url']);
web = ctx.get_web();
props = web.get_allProperties();
webPermissions = web.get_roleAssignments();
ctx.load(web,'Title');
if(getMetadata)
ctx.load(props);
ctx.load(webPermissions,'Include(Member,RoleDefinitionBindings)');
ctx.executeQueryAsync(onQuerySucceededRetrieveRootProperties, onQueryFailedRetrieveRootProperties);
}
function onQuerySucceededRetrieveRootProperties(){
$("#progressMessages").html("").append("<img src='/teams/ITE/Office365/eZShare/SiteAssets/loading.gif'/> Retrieving information of the Site Collection");
structure['Title'] = web.get_title();
if(getMetadata){
var allProps = props.get_fieldValues();
structure['bagProperties'] = {};
for (var prop in allProps) {
if(prop.startsWith('IDB')){
structure['bagProperties'][prop] = allProps[prop];
}
}
}
if(getSecurity){
var permissionsEnumerator = webPermissions.getEnumerator();
var permissions = {};
while (permissionsEnumerator.moveNext()) {
var permission = permissionsEnumerator.get_current();
var rolesEnumerator = permission.get_roleDefinitionBindings().getEnumerator();
while (rolesEnumerator.moveNext()) {
var role = rolesEnumerator.get_current();
if(spRoles.indexOf(role.get_name())==-1){
permissions[permission.get_member().get_title()] = role.get_name();
if($.inArray(permission.get_member().get_title(), listMembers) == -1)
listMembers.push(permission.get_member().get_title());
}
}
}
}
defaultsDepth = listDefaults.length;
securityDepth = listMembers.length;
console.log(structure);
console.log('finished');
createTableHtml();
}
function onQueryFailedRetrieveRootProperties(sender, args){
/*alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());*/
console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
createTableHtml();
}
function renderSecurityHeader(renderGroups){
var table = "";
if(getSecurity){
if(renderGroups){
if(listMembers.length>0){
for(var j=0; j< listMembers.length;j++){
if(j==listMembers.length-1)
table += "<td style='background:#0B3861;color:#fff;border:0;border-right: 2px solid #ddd;' align='center' class='rotate'><div><span>" + listMembers[j] + "</span></div></td>";
else
table += "<td style='background:#0B3861;color:#fff;border:0;' align='center' class='rotate'><div><span>" + listMembers[j] + "</span></div></td>";
}
}else{
table += "<td style='background:#0B3861;color:#fff;border:0;border-right: 2px solid #ddd;'></td>";
}
}else{
for(var i =0; i < securityDepth;i++){
if(i==securityDepth-1)
table += "<td style='background:#0B3861;color:#fff;border:0;border-right: 2px solid #ddd;'></td>";
else
table += "<td style='background:#0B3861;color:#fff;border:0;'></td>";
}
}
}
return table;
}
function renderSecurityBody(structureObject){
var table = "";
if(getSecurity){
if(structureObject != null){
if("Permissions" in structureObject){
if(Object.keys(structureObject["Permissions"]).length > 0){
for(var j=0;j<listMembers.length;j++){
if(j==listMembers.length-1){
if(listMembers[j] in structureObject["Permissions"])
table += "<td style='color:#1c1c1c;max-width:150px;border-right: 2px solid #0B3861;' align='center'>" + ezPermissions[structureObject["Permissions"][listMembers[j]]] + "</td>";
else
table += "<td style='color:#1c1c1c;background:#E6E6E6;border-right: 2px solid #0B3861;' align='center'>0</td>";
}else{
if(listMembers[j] in structureObject["Permissions"]){
table += "<td style='color:#1c1c1c;max-width:150px;' align='center'>" + ezPermissions[structureObject["Permissions"][listMembers[j]]] + "</td>";
}
else{
table += "<td style='color:#1c1c1c;background:#E6E6E6;' align='center'>0</td>";
}
}
}