forked from CERTCC/SSVC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssvc.js
2202 lines (2108 loc) · 66.2 KB
/
ssvc.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
/* SSVC code for graph building */
const _version = "5.1.4"
const _tool = "Dryad SSVC Calculator "+_version
var showFullTree = false
var diagonal,tree,svg,duration,root
var treeData = []
/* Deefault color array of possible color options */
var acolors = ["#28a745","#ffc107","#EE8733","#dc3545","#ff0000","#aa0000","#ff0000"]
var lcolors = {"Track":"#28a745","Track*":"#ffc107","Attend":"#EE8733","Act":"#dc3545"}
var ssvc_short_keys = {};
/* These variables are for decision tree schema JSON aka SSVC Provision Schema */
var export_schema = {decision_points: [],decisions_table: [], lang: "en",
version: "2.0", title: "SSVC Provision table"}
/* If a new analysis is being done use this for export */
var current_score = [];
var current_tree = "CISA-Coordinator-v2.0.3.json";
var current_schema = "SSVC_Computed_v2.03.schema.json";
/* A dictionary of elements that are children of a decision point*/
var ischild = {};
var isparent = {};
/* Default keyword for final step in the tree will be Decision with
class .Decision for rendering */
var final_keyword = "Decision";
/* Outcome of the final decision when a SSVC value has been calculated*/
var final_outcome = "Unknown";
/* Extend jQuery to support simulate D3 click events */
jQuery.fn.simClick = function () {
this.each(function (i, e) {
var evt = new MouseEvent("click");
e.dispatchEvent(evt);
});
};
function reset_form() {
/* This is to clear stupid Firefox cached form values*/
$('select').prop('selectedIndex',0);
$('input[type="file"]').hide();
$('input').val('');
$('select').prop('selectedIndex',0);
$('input[type="file"]').hide();
}
$(function () {
reset_form();
$('#topalert').width($('main').width());
window.onresize = function() { $('#topalert').width($('main').width())}
$('[data-toggle="tooltip"]').tooltip();
if(localStorage.getItem("beenhere")) {
tooltip_cycle_through();
} else {
$('#helper').show();
localStorage.setItem("beenhere",1);
}
//load_tsv_score();
//tree_process("CISA-Coordinator-v2.01.json");
$.getJSON(current_tree).done(function(idata) {
parse_json(idata);
}).fail(function() {
console.log("Failed to Load CISA tree. Loading default tree");
});
export_tree();
load_tsv_score();
})
var raw = [];
document.onkeyup = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) {
console.log("Escape hit")
$('.tescape').fadeOut()
}
}
function cve_table_toggle() {
$('#cve_table').toggleClass('d-none')
if($('#cve_table').hasClass('d-none'))
$('#table_toggle').html("⊕")
else
$('#table_toggle').html("⊖")
}
function tooltip_cycle_through() {
var tips = ['#dt_start','#dt_full_tree','#dt_clear']
$(tips[0]).tooltip('show')
var itip =1
var ix = setInterval(function() {
$('button').tooltip('hide')
$(tips[itip]).tooltip('show')
itip++
if(itip > tips.length) {
clearInterval(ix)
$('button').tooltip('dispose')
}
},1300)
}
function dynamic_mwb() {
var mpdata = $('#mwb').data('parent');
var mcdata = {}
$('#mwb select').each(
(i,k) => {
var opchoice = $(k).val();
var cdata = $(k).data('moptions');
if('label' in cdata) {
/* Global variable for export then local var*/
var tscore = {};
tscore[cdata['label']] = opchoice;
mcdata[cdata['label']] = opchoice;
current_score.push(tscore);
} else {
console.log("Error cannot find relationship information with label");
}
});
var keys_match = Object.keys(mcdata).length
var result = "Unknown/Error";
var soptions = mpdata.options
find_score:
for(var i=0; i<soptions.length; i++) {
if('child_combinations' in soptions[i]) {
var spt = soptions[i]['child_combinations'];
for(var j=0; j<spt.length; j++) {
var current_match = {};
for(var k=0; k < spt[j].length; k++) {
if(('child_label' in spt[j][k]) && (spt[j][k].child_label in mcdata)) {
var spk = spt[j][k]
var myopt = mcdata[spt[j][k].child_label];
if(spk.child_option_labels.findIndex(
x => x == myopt) > -1) {
current_match[spt[j][k].child_label] = 1;
if(Object.keys(current_match).length == keys_match) {
result = soptions[i].label;
break find_score;
}
}
}
}
}
}
}
$('#wscore').html(result);
$('#wsdiv').show();
$('circle[nameid="'+result.toLowerCase()+'"]').parent().simClick();
$('#wsdiv').fadeOut('slow');
setTimeout(function() {
$('#mwb').modal('hide');
}, 400)
}
function export_show(novector) {
var ptranslate = "translate(120,-250)";
if(window.innerWidth <= 1000)
ptranslate = "translate(30,-90) scale(0.4,0.4)";
d3.select("#pgroup").transition()
.duration(600).attr("transform", ptranslate);
var q = $('#exporter').html()
$('#graph').append(q)
if($('#cve_samples').val().match(/^(cve|vu)/i))
$('.exportId').val($('#cve_samples').val())
if(novector == true)
return
setTimeout(make_ssvc_vector,1000);
}
function make_ssvc_vector() {
var tstamp = new Date()
var labels = current_score.map(x => Object.keys(x)[0]);
var vals = current_score.map((x,i) => x[labels[i]]);
labels.push(final_keyword);
/* last node in graph */
var final_outcome = $('#graph svg g.node text:last').text();
vals.push(final_outcome);
/* SSVCv2/Ps:Nm/T:T/U:E/1605040000/
For a vulnerability with no or minor Public Safety Impact,
total Technical Impact, and efficient Utility,
which was evaluated on Nov 10, 2020. */
var computed = "SSVCv2/"
var ochoice = labels.map((k, i) => {
var ox = {}
ox[k] = vals[i]
var lhs = k[0].toUpperCase()
if (k in ssvc_short_keys)
lhs = ssvc_short_keys[k]
var rhs = vals[i][0].toUpperCase()
if(vals[i] in ssvc_short_keys)
rhs = ssvc_short_keys[vals[i]]
computed = computed + lhs+":"+rhs+"/"
return ox
})
/* Save the ochoice object for Export to JSON*/
$('#graph .Exporter').attr('data-ochoice',JSON.stringify(ochoice))
/* new Time string will be ISO 8601 "2021-09-28T21:46:38Z"
q=new Date().toISOString().replace(/\..*$/,'Z') */
//computed = computed + String(parseInt(tstamp.getTime()/1000))+"/"
var q = new Date().toISOString().replace(/\..*$/,'Z');
computed = computed+q+"/"
$('.ssvcvector').html(computed);
}
function export_tree() {
/* First column is the decision in this tree */
var toptions = []
var yhead = [final_keyword]
var yprops = {}
export_schema.decisions_table = raw.filter(x => {
if (x.name.split(":").length > 4)
return true
else {
var t = x.name.split(":")[0]
if(!(t in yprops)) {
yprops[t] = 1
yhead.push(t)
}
return false
}
}).map(x => x.name.split(":").
reduce((z,y,i) => {
z[yhead[i]] = y
if(!toptions[i]) {
toptions[i] = [{label: y, description: y}]
}
else if (!toptions[i].find(t => t.label == y))
toptions[i].push({label: y, description:y})
return z
},{}))
/* Now the decision points should be moved to the end of the array */
yhead.push(yhead.shift())
toptions.push(toptions.shift())
export_schema.decision_points = yhead.map((a,i) => {
var ax = {label: a, decision_type: "simple", options: toptions[i]}
return ax
})
//console.log(toptions)
//export_schema.decisions = tdecisions.map((x,i) => Object.assign(x,{color: acolors[i]}))
/*
export_schema.decisions = Object.keys(tdecisions).map((n,i) => {
return {label: n, description: n, color:acolors[i]}})
*/
//return allrows;
/* "[{"Exploitation":"none"},{"Utility":"partial"},
{"TechnicalImpact":"laborious"},{"SafetyImpact":"none"},
{"Decision":"defer"}]" */
}
function export_json() {
var includetree = $('#graph .includetree').is(':checked')
$('.Exporter').css({'pointer-events':'none'});
var tstamp = new Date()
var oexport = { role: $('#graph .exportRole').val() || "Unknown",
id: $('#graph .exportId').val() || "Unspecified",
version: "2.0",
generator: _tool
}
oexport['computed'] = $('#graph .ssvcvector').html();
oexport['timestamp'] = $('#graph .ssvcvector').html().split('/').
slice(-2,-1)[0]
final_outcome = $('#graph svg g.node text:last').text();
/* Copy current_score as is to options that were selected */
oexport['options'] = current_score;
var last_option = {};
last_option[final_keyword] = final_outcome;
oexport['options'].push(last_option);
oexport['$schema'] = location.origin + location.pathname + current_schema
oexport['decision_tree_url'] = location.origin + location.pathname +
current_tree;
var a = document.createElement("a")
var download_filename = oexport.id+"_"+oexport.role+"_json.txt"
if (includetree) {
oexport['decision_tree'] = export_schema
download_filename = "tree_and_path-"+ oexport.id + "_" + oexport.role +
"_json.txt"
}
a.href = "data:text/plain;charset=utf-8,"+
encodeURIComponent(JSON.stringify(oexport,null,2))
a.setAttribute("download", download_filename)
a.click()
a.remove()
$('.Exporter').css({'pointer-events':'all'});
}
function readFile(input) {
var file = input.files[0];
var reader = new FileReader();
//console.log(file)
reader.readAsText(file);
reader.onload = function() {
//console.log(reader)
//console.log(reader.result);
try {
if(input.id == "dtreecsvload") {
if(file.name.match(/\.json$/i))
parse_json(reader.result)
else
parse_file(reader.result)
}
else
tsv_load(reader.result)
}catch(err) {
reset_form();
topalert("Reading data in file as text failed, Sorry check format"+
" and try again!","danger")
console.log(err)
}
};
reader.onerror = function() {
console.log(reader.error);
topalert("Reading data in file as text failed","danger")
};
}
function topalert(msg,level) {
if(!level)
level = "info"
var mw = $('#topalert').parent().width()
$('#topalert').width(String(mw)+"px");
$('#topalert').html(msg).removeClass().addClass("alert alert-"+level,msg).fadeIn("fast",function() {
$(this).delay(2000).fadeOut("slow"); })
}
function tree_process(w) {
var ptree = $(w).val()
if(ptree == "import") {
if(navigator.userAgent.indexOf("Chrome") < 0) {
$('#dtreecsvload').show()
$('#dtreecsvload').click()
topalert("Choose the file to upload below")
} else
$('#dtreecsvload').click()
return
}
$.get(ptree, function(idata) {
if(ptree.match(/\.json$/i))
parse_json(idata)
else
parse_file(idata)
/* remove .json from the name. This method uses the file name */
var ptree_name = ptree.replace(/\.[^\.]+$/,'')
$('.cover_heading_append').html('('+ptree_name+')');
})
}
function create_permalink(copyme){
$('.permalink').removeClass('d-none');
var purl = location.origin+location.pathname+"#"+
$("#graph .ssvcvector").html()
var uparts = [".ssvcvector",".exportId",".exportRole"]
for (var i=0; i<uparts.length; i++) {
if($("#graph "+uparts[i]).val()) {
purl = purl +"&"+$("#graph "+uparts[i]).val()
}
}
$("#graph .permalink").html(purl);
if(copyme)
copym($("#graph .permalink")[0],true);
else
return purl;
}
function finish_permalink(plparts,pchildren) {
if(pchildren && pchildren.length > 0) {
var index = pchildren[0]['index']
current_score.splice(index,0,...pchildren.map(x => {
var y = {};
y[x.childlabel] = x.childval;
return y;
}));
}
var ptranslate = "translate(120,-250)"
if(window.innerWidth <= 1000)
ptranslate = "translate(30,-90) scale(0.4,0.4)"
d3.select("#pgroup").transition()
.duration(600).attr("transform", ptranslate)
setTimeout(function() {
export_show(true)
if(plparts[0])
$('#graph .ssvcvector').html(plparts[0]);
if(plparts[1])
$('#graph .exportId').val(plparts[1])
if(plparts[2])
$('#graph .exportRole').val(plparts[2]);
$('#biscuit').fadeOut()
}, 800)
}
function permalink() {
if(location.hash == "")
return;
topalert("Now loading permalink URL parameters","success");
dt_clear();
dt_start();
try {
$('#biscuit').fadeIn();
var plink = location.hash.substr(1);
var pchildren = [];
var plparts = plink.split("&");
var fm = plparts[0].split("/");
$("#mwb").attr("data-override",1);
/* "SSVCv2/E:A/V:S/T:T/M:H/D:C/1632171335/&CVE-2014-01-01&Coordinator"
OR
"SSVCv2/E:A/V:S/T:T/M:H/D:C/2021-01-09/&CVE-2014-01-01&Coordinator" */
var sI = {}
var last_precheck = ""
for(var i=1;i<fm.length-2;i++) {
var dtup = fm[i].split(":");
var fstep = export_schema.decision_points.filter(x => x.key == dtup[0]);
if(fstep.length != 1) {
console.log("This decision point does not exist");
console.log(dtup);
continue;
}
var fopt = fstep[0].options.filter(x => x.key == dtup[1]);
if(fstep[0].label in ischild) {
console.log("This is a child decision, do it later");
pchildren.push({
index: i-1,
childlabel: fstep[0].label,
childval: fopt[0].label
});
continue;
}
var precheck = fopt[0].label.toLowerCase();
sI[precheck] = setInterval(
function(u) {
if($('.prechk-'+u).length == 1) {
$('.prechk-'+u).simClick();
clearInterval(sI[u]);
delete sI[u];
if(u == last_precheck)
finish_permalink(plparts,pchildren);
return;
}
},600*i,precheck);
last_precheck = precheck;
}
setTimeout(function() {
for (let k in sI) {
console.log("Pending jobs incomplete after 20 seconds");
clearInterval(sI[k]);
delete sI[k];
}
},20000)
console.log(sI);
}catch(err) {
console.log(err);
topalert("Failed to parse Permalink URL!","error")
}
}
function process(w) {
var cve = $(w).val()
if(cve == "import") {
if(navigator.userAgent.indexOf("Chrome") < 0) {
$('#cvetsvload').show()
topalert("Choose the file to upload below")
} else
$('#cvetsvload').click()
return
}
var cve_data = $('#'+cve).data()
if(!cve_data) {
alert("Some error in loading this CVE data check the template and try again")
return
}
dt_clear();
$('#biscuit').fadeIn();
dt_start();
$('#cve_table tbody tr td').remove()
var steps = ['Exploit','Virulence','Technical']
var stimes = [1600,3200,5100]
//console.log(new Date().getTime())
for(var i=0; i< steps.length; i++) {
clickprocess(steps[i],cve_data,stimes[i])
}
$('#biscuit').fadeOut(4930)
for(var k in cve_data)
$('#cve_table tbody tr').append("<td class='d-temp'>"+cve_data[k]+"</td>")
$('#table_toggle').show()
}
function clickprocess(tstep,cve_data,stime) {
setTimeout(function() {
//console.log(tstep)
//console.log(stime)
//console.log(new Date().getTime())
if(tstep in cve_data) {
if($(".prechk-"+cve_data[tstep].toLowerCase()).length == 1) {
$(".prechk-"+cve_data[tstep].toLowerCase()).simClick()
} else {
console.log("Try again in a few seconds "+tstep)
//clickprocess(tstep,cve_data,stime-1000)
}
} else {
console.log("Some strange error "+tstep)
console.log(cve_data)
}
},stime)
}
function load_tsv_score() {
$.get("sample-ssvc.txt",tsv_load);
}
function tsv_load(data) {
var rmv = $('#cve_samples option:nth-child(n+3)').remove().length
$('#cve_table thead tr th').remove()
var y = data.split("\n")
var heads = y.shift().split("\t")
var scores = y.map(x => { return x
.split("\t")
.reduce((map,obj,i) => {
map[heads[i]] = obj; return map;
},{}) })
.filter(x => 'CVE' in x && x.CVE.length > 3)
.sort(function(a, b) { if(a.CVE < b.CVE) return -1; else return 1})
for(var i=0; i<scores.length;i++) {
if(!('CVE' in scores[i])) continue
$('#cve_samples').append($("<option></option>")
.attr("id",scores[i].CVE)
.text(scores[i].CVE)
.data(scores[i]))
}
$('#cve_samples').removeClass("d-none").addClass("form-control cve_samples")
for(var i=0; i<heads.length;i++)
$('#cve_table thead tr').append("<th>"+heads[i]
.replace(/(\([^)]+\))/,
'<br><span class="text-muted">$1</span>')+
"</th>")
if(rmv)
topalert("Loaded TSV CVE samples count of "+scores.length,"success")
}
function create_short_keys(x,uniq_keys) {
/* If a key is provided for short_key representation use it
if not detect one using the last */
if("key" in x) {
ssvc_short_keys[x.label] = x.key
return true;
}
else {
var iuniq = 0
ssvc_short_keys[x.label] = x.label[0].toUpperCase()
while (x.label[iuniq] in uniq_keys) {
iuniq = iuniq + 1;
ssvc_short_keys[x.label] = x.label[iuniq].toUpperCase()
}
uniq_keys[x.label[iuniq]] = 1;
/* Create a key if one does not exist for reference in the full
exported JSON */
x["key"] = ssvc_short_keys[x.label];
}
}
function parse_json(xraw,paused) {
var zraw = [];
isparent = {};
var tm;
if(typeof(xraw) == "string")
tm = JSON.parse(xraw)
else
tm = xraw
if('decision_tree' in tm) {
/* This has a decision_tree and a score - a computed and provision
schemas together*/
tm = tm.decision_tree;
}
if(!('decision_points' in tm)) {
topalert("JSON schema has no decision_points","danger")
return
}
if(!('decisions_table' in tm)) {
topalert("JSON schema has no decision table, we can't help you with that","danger");
console.log(tm);
return;
}
/* Save JSON for export*/
export_schema = tm
/* This is temp key to find full child elements */
var xkeys = {};
/* Find array that are children as children will also have the decision
type simple */
ischild = tm.decision_points.reduce(
(x,y) => {
/* Use either key or label to create a hash of everyone */
xkeys[y.label] = y;
if("key" in y)
xkeys[y.key] = y.label
/* Use either key or label to mark the xkeys to a child
decision tree */
if("children" in y) {
console.log("Children for "+y.label);
isparent[y.label] = [];
y.children.map(z => {
var tx = z.label;
if(("key" in z) && (z.key != "")) {
tx = xkeys[z.key];
}
isparent[y.label].push(xkeys[tx]);
x[tx] = 1;
});
}
return x;
},{});
/* Check to make sure neither key nor label is in a ischild object */
var x = tm.decision_points.filter(
x => (!(x.label in ischild))).map(r => r.label)
var y = tm.decisions_table
//console.log(y)
var yraw = [...Array(x.length)].map(u => [])
var id = 1
var thash = {}
var decisions = tm.decision_points.filter(x => x.decision_type == "final")
if('title' in tm)
$('.cover_heading_append').html('('+tm.title+')');
if(decisions.length != 1) {
topalert("JSON schema has no decisions marked as final, assuming the last element is the \"Final\" decision.","warning")
tm.decision_points[tm.decision_points.length - 1]['decision_type'] = "final"
decisions = [tm.decision_points[tm.decision_points.length - 1]]
}
final_keyword = decisions[0].label
//console.log(decisions)
//console.log(final_keyword)
for(var i=0; i<y.length; i++) {
//var tname = y[i].pop()+":"+y[i].join(":")
//console.log(y[i])
/* Decision table should have the "outcome" or "decision" fiel if not skip
this entry */
if(!(final_keyword in y[i]))
continue
var tname = y[i][final_keyword]+":"+x.map(t => y[i][t]).slice(0,-1).join(":")
for( var j=0; j< x.length-1; j++) {
//var tparent = x[x.length-2-j]+":"+y[i].slice(0,x.length-2-j).join(":")
var tparent = x[x.length-2-j]+":"+x.slice(0,x.length-2-j).map(q => y[i][q]).join(":")
//var tparent = x[x.length-1-j]+":"+x.slice(0,x.length-1-j).map(q => y[i][q]).join(":")
if(!(tname in thash))
var yt = {name:tname.replace(/\:+$/,''),id:id++,parent:tparent.replace(/\:+$/,''),props:"{}",children:[]}
else
continue
thash[yt.name] = 1
tname = tparent
yraw[j].push(yt)
}
}
for(var j=yraw.length; j> -1; j--) {
if(yraw.length > 0)
zraw = zraw.concat(yraw[j])
}
/* Top or the first part of the tree data */
zraw[0] = {name:x[0],id:id+254,children:[],parent:null,props:"{}"}
/* yraw[0].push({name:"Exploitation:",id:1024,children:[],parent:null,props:"{}"}) */
raw = zraw
//console.log(raw)
topalert("Decision tree JSON has been updated with "+raw.length+
" nodes, with "+y.length+" possible outcomes, You can "+
"use it now!","success")
dt_clear()
/* Create label fields if they exists*/
var lastdiv = "";
/* Unique keys for decision points*/
var duniq_keys = {};
/* unique keys for choices under decision points*/
var ouniq_keys = {};
tm.decision_points.map(x => {
create_short_keys(x,duniq_keys);
var options_data = {}
var options_html = x.options.reduce((h,r) => {
create_short_keys(r,ouniq_keys);
options_data[r.label] = r.description;
var rlabel = r.label[0].toLocaleUpperCase()+r.label.substr(1);
var spclass = 'popup-'+safedivname(r.label);
var div_add = "<div class='popupidiv "+spclass+"'><b>"+rlabel+"</b> "+r.description+"<hr /></div>";
return h + div_add;
},"<h5>"+x.label+"</h5>")
var hdiv = safedivname(x.label)
if($("."+hdiv).length != 1) {
//console.log(hdiv,"new");
$("."+hdiv).remove();
$('body').append($('<div/>').addClass("d-none "+hdiv));
}
$("."+hdiv).html(options_html)
if(x.label in isparent) {
/* Save the entier decision object in data parent value*/
$('#mwb').attr("data-parent",JSON.stringify(x));
$("."+hdiv+" h5").after("<p>(Complex Decision)</p>");
//console.log(isparent[x.label]);
$("#mwb h5").html(x.label + " (Cummulative Score)");
//('#wbtable tr')
$("#wbtable tr").remove();
isparent[x.label].forEach( (t,k) => {
var stdiv = safedivname(t.label);
var tselect = $("<select/>").addClass("form-control s-"+stdiv).
attr("data-moptions",JSON.stringify(t));
t.options.forEach((v,l) => {
tselect.append($("<option/>").attr({
"value":v.label}).text(v.label));
});
var tlabel = $("<span>").html(t.label+" ")
.append($("<a/>").attr({
"class": "circletext",
"onmouseover": "shwhelp(this)",
"onmouseout": "hidediv(this)",
"data-tdiv": stdiv,
"href": "javascript:void(0)"
}).html("?"))
var tr = $("<tr/>").append($("<td/>").append(tlabel)).
append($("<td/>").append(tselect));
$("#wbtable").append(tr);
var addcontent = "<blockquote>Depends on "+String(k+1)
addcontent += $("."+stdiv).html()+"</blockquote>";
$("."+hdiv).append(addcontent);
$('#mwb .btn-primary').removeAttr('onclick');
$('#mwb .btn-primary').attr({'onclick': 'dynamic_mwb()'});
});
}
lastdiv = hdiv
//console.log(options_data);
$("."+hdiv).attr("data-options",JSON.stringify(options_data));
});
$("."+lastdiv).addClass("Decision");
var classes = []
var decision_div = decisions[0].options.reduce((h,r,ir) => {
classes.push(safedivname(r.label));
if(("color" in r) && (r.color)) {
lcolors[r.label] = r.color;
} else if(acolors[i]) {
r.color = acolors[i];
}
return h + $("<div>").append($("<strong/>").addClass("decisiontab").
css({color:r.color}).html(r.label))
.append(" "+r.description+"<hr>").html();
},"<h5>"+final_keyword+"</h5>")
if($("."+classes[0]).length != 1) {
$("."+classes[0]).remove()
$('body').append($('<div/>').addClass("d-none "+classes[0]))
}
//console.log(classes)
//console.log(decision_div)
$("."+classes[0]).addClass(classes.join(" ")).html(decision_div)
permalink();
$('#dtreecsvload').hide();
}
function shwhelp(w) {
var iconPos = w.getBoundingClientRect();
var tm = $(w).data('tdiv')
if(tm) {
$('#mpopup').css({left:(iconPos.right + 10) + "px",
top:(window.scrollY + iconPos.top - 20) + "px",
"max-width": "-moz-available",
"max-width": "-webkit-fill-available",
"max-width": "stretch",
"overflow-y": "auto",
"z-index":1050,
display:"block"});
$('#mpopup').html($('.'+tm).html())
$('#mwb').on('hidden.bs.modal', function (e) {
$('#mpopup').hide();
})
}
$('#mpopup').show()
}
function safedivname(instr) {
var uri_esc = encodeURIComponent(instr)
var safestr = btoa(uri_esc.replace(/%([0-9A-F]{2})/g,
(m, p) =>
String.fromCharCode('0x' + p)));
var fstr = "d-"+safestr.replace(/[\+\/\=]/gi,
(m,p) => { return m.charCodeAt(0) });
return fstr.substr(0,14);
}
function create_export_schema_dtable(yi,x) {
export_schema.decisions_table.push(yi.reduce((a,b,c) => {
/* Add labels that do not exist */
if(export_schema.decision_points[c]['options']
.filter(d => ('label' in d) && (d.label == b)).length != 1)
export_schema.decision_points[c]['options'].push({label: b, description:b})
a[x[c]] = b
return a; },{}))
}
function parse_file(xraw) {
/* This is really parse csv instead of parse JSON */
//var xraw = 'TSV data'
var zraw=[]
export_schema.decision_points = []
export_schema.decisions_table = []
/* CSV or TSV looks like
ID,Exploitation,Utility,TechnicalImpact,SafetyImpact,Outcome
*/
var xarray = xraw.split('\n')
var xr = xarray.map(x => x.split(/[\t,]+/))
/* Remove first row has the headers and pass the rest to variable y */
var y = xr.splice(1)
/* Check if rowID first column of second row to match not number*/
var is_ssvc_v1 = y[0][0].match(/\D+/) ? false : true
/* Remove ID column in the first row to create x*/
if (is_ssvc_v1)
var x = xr[0].splice(1)
else
var x = xr[0]
/* Now xr looks like below for ssvc csv v1 */
/* [["Row", "Exploitation", "Virulence", "Technical", "Mission_Well-being", "Decision"]] */
//var yraw = [[],[],[],[],[]]
/* Register the export schema decision points, assume all decisions are simple */
export_schema.decision_points = x.map(
dc => {
var ix = {decision_type:"simple", options:[]}
ix.label = dc
return ix
})
/* make the last column final decision/outcome/action */
export_schema.decision_points[export_schema.decision_points.length-1].decision_type="final"
/* Initialize Empty arrray */
var yraw = [...Array(x.length)].map(u => []);
var id=1;
/* This will create just the last branches of the tree */
var thash = {}
for(var i=0; i< y.length - 1; i++) {
if(y[i].length < 1) continue
/* Remove ID column if it is SSVC v1*/
if(is_ssvc_v1)
y[i].shift()
/* Add lame CSV/TSV data to export schema */
//console.log(y[i]);
create_export_schema_dtable(y[i],x)
var tname = y[i].pop()+":"+y[i].join(":")
//console.log(tname)
if(tname == "undefined") continue;
for( var j=0; j< x.length-1; j++) {
/*y[i] look like 0,none,laborious,partial,none,defer */
var tparent = x[x.length-2-j]+":"+y[i].slice(0,x.length-2-j).join(":")
//console.log(tparent)
if(!(tname in thash))
var yt = {name:tname.replace(/\:+$/,''),id:id++,parent:tparent.replace(/\:+$/,''),props:"{}",children:[]}
else
continue
thash[yt.name] = 1
tname = tparent
yraw[j].push(yt)
}
}
/* This step below is not necessary now as the above routine goes from
0 -> y.length, instead of 0 to y.length -1.
Remove ID column and Add the last row into export schema */
//y[y.length-1].shift()
//create_export_schema(y[y.length-1],x)
for(var j=yraw.length; j> -1; j--) {
if(yraw.length > 0)
zraw = zraw.concat(yraw[j])
}
/* Next part of the tree data */
zraw[0] = {name:x[0],id:id+254,children:[],parent:null,props:"{}"}
/* yraw[0].push({name:"Exploitation:",id:1024,children:[],parent:null,props:"{}"}) */
raw = zraw
var detect_version = "v2"
if(is_ssvc_v1)
detect_version = "v1"
topalert("Decision tree has been updated with "+raw.length+" nodes, with "+
y.length+" possible decisions using "+detect_version+" CSV/TSV file, You can use it now!","success")
dt_clear()
export_schema.decision_points[export_schema.decision_points.length-1].
options.map((x,i) => lcolors[x.label] = acolors[i] )
}
function add_invalid_feedback(xel,msg) {
$('.invalid-feedback').remove()
$('.valid-feedback').remove()
if(msg == "")
msg = 'Please provide valid data for '+$(xel).attr('name')
var err = $('<div>').html(msg)
$(xel).after(err)
$(err).addClass('invalid-feedback').show()
$(xel).focus()
}
function add_valid_feedback(xel,msg) {
$('.invalid-feedback').remove()
$('.valid-feedback').remove()
if(msg == "")
msg = 'Looks good'
var gdg = $('<div>').html(msg)
$(xel).after(gdg)
$(gdg).addClass('valid-feedback').show()
}
function verify_inputs() {
var inputs=$('#main_table :input').not('button')
for (var i=0; i< inputs.length; i++) {
if(!$(inputs[i]).val()) {
if(!$(inputs[i]).hasClass("not_required")) {
add_invalid_feedback(inputs[i],"")
return false
}
}
}
return true
}
function generate_uuid() {
var uuid = Math.random().toString(16).substr(2,8)
for (var i=0; i<3; i++)
uuid += '-'+Math.random().toString(16).substr(2,4)
return uuid+'-'+Math.random().toString(16).substr(2,12)
}
function draw_graph() {
var margin = {top: 20, right: 120, bottom: 20, left: 120},
width = 1060 - margin.right - margin.left,
height = 800 - margin.top - margin.bottom
if(showFullTree) {
var add_offset = 0
if(raw.length > 60 )
add_offset = (raw.length - 60)*5
//margin.left = margin.left + (raw.length - 60)*2
//width = 1200 - margin.right - margin.left + add_offset*0.5
height = 1300 - margin.top - margin.bottom + add_offset
}
duration = 750
tree = d3.layout.tree()
.size([height, width]);
diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; });
//xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
var default_translate = "translate(" + margin.left + "," + margin.top + ")"
var svg_width = width + margin.right + margin.left
var svg_height = height + margin.top + margin.bottom
if(window.innerWidth <= 1000) {
default_translate = "translate(10,0) scale(0.75)"
if(window.innerWidth <= 750)
default_translate = "translate(30,0) scale(0.42)"
}
svg = d3.select("#graph").append("svg")
.attr("xmlns","http://www.w3.org/2000/svg")
.attr("preserveAspectRatio","none")
.attr("class","mgraph")
.attr("width", svg_width)
.attr("height", svg_height)
.append("g")
.attr("transform", default_translate)
.attr("id","pgroup")
root = treeData[0];
root.x0 = height / 2;
root.y0 = 0;
update(root)
d3.select(self.frameElement).style("height", "700px");
/*
var svgx = $('svg')[0].outerHTML
$('#dlsvg').attr('href','data:image/svg+xml;charset=utf-8,'+ encodeURIComponent(svgx))
$('#dlsvg').attr('download','SVG-'+timefile()+'.svg')
*/
}
function check_children(d,a,b) {
if((d.children) && (d.children.length)) return a
if((d._children) && (d._children.length)) return a
return b
}
function update(source) {
var i = 0
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse()
var links = tree.links(nodes)
// Normalize for fixed-depth.
nodes.forEach(function(d) { d.y = d.depth * 200;})
// Update the nodes…
var node = svg.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
// Enter any new nodes at the parent's previous position.
var nodeEnter = node.enter().append("g")
.attr("class", "node bof")
.attr("transform", function(d) {
return "translate(" + source.y0 + "," + source.x0 + ")";
})
.attr("class", function(d) {
if('depth' in d)
return "node depth-"+String(d.depth);
return "node depth-none";})
.on("click", doclick)
.on("contextmenu",dorightclick)
.on("mouseover",showdiv)
.on("mouseout",hidediv);
nodeEnter.append("circle")
.attr("r", 1e-6)
.attr("class","junction gvisible")
.style("fill", function(d) {
if(d._children) return "lightsteelblue"
if(!('children' in d)) {
/* Last node no children */
var dname = d.name.split(":").shift();
if(dname in lcolors)
return lcolors[dname];
}
return "#fff"
} );
/*
nodeEnter.append("text")
.attr("x", function(d) { return check_children(d,"-13","-60")})
.attr("y", "+10")
.attr("dy", ".35em")
.attr("class","dfork")
.attr("text-anchor", function(d) { return check_children(d,"end","start") })