/* Codacy comment to notify that baseurl is a read-only global variable. */ /* global baseurl */ String.prototype.ucfirst = function() { return this.charAt(0).toUpperCase() + this.slice(1); } if (!String.prototype.startsWith) { String.prototype.startsWith = function(searchString, position) { position = position || 0; return this.indexOf(searchString, position) === position; }; } function stringToRGB(str){ var hash = 0; if (str.length == 0) return hash; for (i = 0; i < str.length; i++) { hash = ((hash<<5)-hash) + str.charCodeAt(i); hash = hash & hash; // Convert to 32bit integer } var c = (hash & 0x00FFFFFF) .toString(16) .toUpperCase(); return "#" + "00000".substring(0, 6 - c.length) + c; } function rgb2hex(rgb) { rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); function hex(x) { return ("0" + parseInt(x).toString(16)).slice(-2); } return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); } function xhrFailCallback(xhr) { if (xhr.status === 403) { showMessage('fail', 'Not allowed.'); } else if (xhr.status === 404) { showMessage('fail', 'Resource not found.'); } else { showMessage('fail', 'Something went wrong - the queried function returned an exception. Contact your administrator for further details.'); } } function deleteObject(type, action, id) { var url = baseurl + "/" + type + "/" + action + "/" + id; $.get(url, function(data) { openPopup("#confirmation_box"); $("#confirmation_box").html(data); }).fail(xhrFailCallback) } function quickDeleteSighting(id, rawId, context) { url = baseurl + "/sightings/quickDelete/" + id + "/" + rawId + "/" + context; $.get(url, function(data) { $("#confirmation_box").html(data); openPopup("#confirmation_box"); }).fail(xhrFailCallback) } function fetchAddSightingForm(type, attribute_id, onvalue) { var url = baseurl + "/sightings/quickAdd/" + attribute_id + "/" + type; if (onvalue) { url = url + "/1"; } else { url = url + "/0"; } $.get(url, function(data) { $("#confirmation_box").html(data); openPopup("#confirmation_box"); }); } function flexibleAddSighting(clicked, type, attribute_id, event_id, placement) { var $clicked = $(clicked); var hoverbroken = false; $clicked.off('mouseleave.temp').on('mouseleave.temp', function() { hoverbroken = true; }); setTimeout(function() { $clicked.off('mouseleave.temp'); if ($clicked.is(":hover") && !hoverbroken) { var html = '
' + '' + '' + '
'; openPopover(clicked, html, true, placement); } }, 1000); } function publishPopup(id, type) { var action = "alert"; if (type == "publish") action = "publish"; if (type == "unpublish") action = "unpublish"; if (type == "sighting") action = "publishSightings"; var destination = 'attributes'; $.get(baseurl + "/events/" + action + "/" + id, function(data) { $("#confirmation_box").html(data); openPopup("#confirmation_box"); }); } function delegatePopup(id) { simplePopup(baseurl + "/event_delegations/delegateEvent/" + id); } function genericPopup(url, popupTarget, callback) { var $popupTarget = $(popupTarget); $.get(url, function(data) { $popupTarget.html(data); $popupTarget.fadeIn(); var left = ($(window).width() / 2) - ($(popupTarget).width() / 2); $popupTarget.css({'left': left + 'px'}); $("#gray_out").fadeIn(); if (callback !== undefined) { callback(); } }); } function screenshotPopup(url, title) { if (!url.startsWith('data:image/')) { url = url.slice(0, -1); } var popupHtml = ''; url = $('
').text(url).html(); title = $('
').text(title).html(); popupHtml += ''; popupHtml += '
'; if (!url.startsWith('data:image/')) { popupHtml += ''; } popupHtml += '
'; // see bottom of image for large one $('#screenshot_box').html(popupHtml); $('#screenshot_box').css({ display: 'block', top: (document.documentElement.scrollTop + 100) + 'px' }); $("#gray_out").fadeIn(); } function submitPublish(id, type) { $("#PromptForm").submit(); } function editTemplateElement(type, id) { simplePopup(baseurl + "/template_elements/edit/" + type + "/" + id); } function cancelPrompt(isolated) { if (isolated == undefined) { $("#gray_out").fadeOut(); } $("#popover_form").fadeOut(); $("#confirmation_box").fadeOut(); $("#confirmation_box").empty(); $('.have-a-popover').popover('destroy'); } function submitDeletion(context_id, action, type, id) { var context = 'event'; if (type == 'template_elements') context = 'template'; var formData = $('#PromptForm').serialize(); $.ajax({ beforeSend: function (XMLHttpRequest) { $(".loading").show(); }, data: formData, success:function (data, textStatus) { if (type == 'eventGraph') { showMessage('success', 'Network has been deleted'); reset_graph_history(); } else { updateIndex(context_id, context); handleGenericAjaxResponse(data); } }, complete:function() { $(".loading").hide(); $("#confirmation_box").fadeOut(); $("#gray_out").fadeOut(); }, type:"post", cache: false, url: baseurl + "/" + type + "/" + action + "/" + id, }); } function removeSighting(caller) { var id = $(caller).data('id'); var rawid = $(caller).data('rawid'); var context = $(caller).data('context'); if (context != 'attribute') { context = 'event'; } var formData = $('#PromptForm').serialize(); $.ajax({ beforeSend: function (XMLHttpRequest) { $(".loading").show(); }, data: formData, success:function (data, textStatus) { handleGenericAjaxResponse(data); var org = "/" + $('#org_id').text(); updateIndex(id, 'event'); $.get(baseurl + "/sightings/listSightings/" + rawid + "/" + context + org, function(data) { $("#sightingsData").html(data); }); }, complete:function() { $(".loading").hide(); $("#confirmation_box").fadeOut(); }, type:"post", cache: false, url: baseurl + "/sightings/quickDelete/" + id + "/" + rawid + "/" + context, }); } function toggleSetting(e, setting, id) { e.preventDefault(); e.stopPropagation(); switch (setting) { case 'warninglist_enable': formID = '#WarninglistIndexForm'; dataDiv = '#WarninglistData'; replacementForm = baseurl + '/warninglists/getToggleField/'; searchString = 'enabled'; break; case 'favourite_tag': formID = '#FavouriteTagIndexForm'; dataDiv = '#FavouriteTagData'; replacementForm = baseurl + '/favourite_tags/getToggleField/'; searchString = 'Adding'; break; case 'activate_object_template': formID = '#ObjectTemplateIndexForm'; dataDiv = '#ObjectTemplateData'; replacementForm = baseurl + '/ObjectTemplates/getToggleField/'; searchString = 'activated'; break; case 'noticelist_enable': formID = '#NoticelistIndexForm'; dataDiv = '#NoticelistData'; replacementForm = baseurl + '/noticelists/getToggleField/'; searchString = 'enabled'; break; } $(dataDiv).val(id); var formData = $(formID).serialize(); $.ajax({ beforeSend: function (XMLHttpRequest) { $(".loading").show(); }, data: formData, success:function (data, textStatus) { var result = data; if (result.success) { var setting = false; if (result.success.indexOf(searchString) > -1) setting = true; $('#checkBox_' + id).prop('checked', setting); } handleGenericAjaxResponse(data); }, complete:function() { $.get(baseurl + replacementForm, function(data) { $('#hiddenFormDiv').html(data); }); $(".loading").hide(); $("#confirmation_box").fadeOut(); $("#gray_out").fadeOut(); }, error:function() { handleGenericAjaxResponse({'saved':false, 'errors':['Request failed due to an unexpected error.']}); }, type:"post", cache: false, url: $(formID).attr('action'), }); } function initiatePasswordReset(id) { $.get(baseurl + "/users/initiatePasswordReset/" + id, function(data) { $("#confirmation_box").html(data); openPopup("#confirmation_box"); }); } function submitPasswordReset(id) { var formData = $('#PromptForm').serialize(); var url = baseurl + "/users/initiatePasswordReset/" + id; $.ajax({ beforeSend: function (XMLHttpRequest) { $(".loading").show(); }, data: formData, success:function (data, textStatus) { handleGenericAjaxResponse(data); }, complete:function() { $(".loading").hide(); $("#confirmation_box").fadeOut(); $("#gray_out").fadeOut(); }, type:"post", cache: false, url:url, }); } function submitMessageForm(url, form, target) { if (!$('#PostMessage').val()) { showMessage("fail", "Cannot submit empty message."); } else { submitGenericForm(url, form, target); } } function submitGenericForm(url, form, target) { $.ajax({ beforeSend: function (XMLHttpRequest) { $(".loading").show(); }, data: $('#' + form).serialize(), success:function (data, textStatus) { $('#top').html(data); showMessage("success", "Message added."); }, complete:function() { $(".loading").hide(); }, error: xhrFailCallback, type:"post", cache: false, url:url, }); } function acceptObject(type, id, event) { var name = '#ShadowAttribute_' + id + '_accept'; var formData = $(name).serialize(); $.ajax({ data: formData, success: function (data, textStatus) { updateIndex(event, 'event'); eventUnpublish(); handleGenericAjaxResponse(data); }, error: xhrFailCallback, type: "post", cache: false, url: baseurl + "/shadow_attributes/accept/" + id, }); } function toggleCorrelation(id, skip_reload) { if (typeof skip_reload === "undefined") { skip_reload = false; } $.ajax({ beforeSend: function (XMLHttpRequest) { $(".loading").show(); }, data: $('#PromptForm').serialize(), success:function (data, textStatus) { handleGenericAjaxResponse(data, skip_reload); $("#correlation_toggle_" + id).prop('checked', !$("#correlation_toggle_" + id).is(':checked')); }, complete:function() { $(".loading").hide(); $("#confirmation_box").fadeOut(); $("#gray_out").fadeOut(); }, type:"post", cache: false, url: baseurl + '/attributes/toggleCorrelation/' + id, }); } function toggleToIDS(id, skip_reload) { if (typeof skip_reload === "undefined") { skip_reload = false; } $.ajax({ beforeSend: function (XMLHttpRequest) { $(".loading").show(); }, data: $('#PromptForm').serialize(), success:function (data, textStatus) { handleGenericAjaxResponse(data, skip_reload); $("#toids_toggle_" + id).prop('checked', !$("#toids_toggle_" + id).is(':checked')); }, complete:function() { $(".loading").hide(); $("#confirmation_box").fadeOut(); $("#gray_out").fadeOut(); }, type:"post", cache: false, url: baseurl + '/attributes/editField/' + id , }); } function eventUnpublish() { $('.publishButtons').show(); $('.exportButtons').hide(); $('.published').hide(); $('.notPublished').show(); } function updateIndex(id, context, newPage) { if (typeof newPage !== 'undefined') page = newPage; var url, div; if (context == 'event') { if (typeof currentUri == 'undefined') { location.reload(); return true; } url = currentUri; div = "#attributes_div"; } if (context == 'template') { url = baseurl + "/template_elements/index/" + id; div = "#templateElements"; } $.ajax({ beforeSend: function () { $(".loading").show(); }, dataType:"html", cache: false, success:function (data, textStatus) { $(".loading").hide(); $(div).html(data); if (typeof genericPopupCallback !== "undefined") { genericPopupCallback("success"); } else { console.log("genericPopupCallback function not defined"); } if (typeof timelinePopupCallback !== "undefined") { timelinePopupCallback("success"); } else { console.log("timelinepopupcallback function not defined"); } }, url: url, }); } function updateAttributeFieldOnSuccess(name, type, id, field, event) { $.ajax({ beforeSend: function () { if (field !== 'timestamp') { $(".loading").show(); } }, dataType:"html", cache: false, success:function (data, textStatus) { if (field !== 'timestamp') { $(".loading").hide(); $(name + '_solid').html(data); $(name + '_placeholder').empty(); $(name + '_solid').show(); } else { $('#' + type + '_' + id + '_' + 'timestamp_solid').html(data); } popoverStartup(); // reactive popovers }, url: baseurl + "/attributes/fetchViewValue/" + id + "/" + field, }); } function updateObjectFieldOnSuccess(name, type, id, field, event) { $.ajax({ beforeSend: function (XMLHttpRequest) { if (field != 'timestamp') { $(".loading").show(); } }, dataType:"html", cache: false, success:function (data, textStatus) { if (field != 'timestamp') { $(".loading").hide(); $(name + '_solid').html(data); $(name + '_placeholder').empty(); $(name + '_solid').show(); } else { $('#' + type + '_' + id + '_' + 'timestamp_solid').html(data); } }, url: baseurl + "/objects/fetchViewValue/" + id + "/" + field, }); } function activateField(type, id, field, event) { resetForms(); if (type === 'denyForm') { return; } var objectType, containerName; if (type === 'Object') { objectType = 'objects'; containerName = 'Object'; } else { objectType = 'attributes'; containerName = 'Attribute'; } var name = '#' + type + '_' + id + '_' + field; var container_name = '#' + containerName + '_' + id + '_' + field; $.ajax({ beforeSend: function() { $(".loading").show(); }, dataType: "html", cache: false, success: function (data) { $(container_name + '_placeholder').html(data); postActivationScripts(name, type, id, field, event); }, url: baseurl + "/" + objectType + "/fetchEditForm/" + id + "/" + field, complete: function() { $(".loading").hide(); }, error: xhrFailCallback }); } function submitQuickTag(form) { $('#' + form).submit(); } //if someone clicks an inactive field, replace it with the hidden form field. Also, focus it and bind a focusout event, so that it gets saved if the user clicks away. //If a user presses enter, submit the form function postActivationScripts(name, type, id, field, event) { $(name + '_field').focus(); inputFieldButtonActive(name + '_field'); if (field == 'value' || field == 'comment') { autoresize($(name + '_field')[0]); $(name + '_field').on('keyup', function () { autoresize(this); }); } $(name + '_form').submit(function(e){ e.preventDefault(); submitForm(type, id, field, event); return false; }); $(name + '_form').bind("focusout", function() { inputFieldButtonPassive(name + '_field'); }); $(name + '_form').bind("focusin", function(){ inputFieldButtonActive(name + '_field'); }); $(name + '_field').closest('.inline-input-container').children('.inline-input-accept').bind('click', function() { submitForm(type, id, field, event); }); $(name + '_field').closest('.inline-input-container').children('.inline-input-decline').bind('click', function() { resetForms(); }); $(name + '_solid').hide(); } function quickEditHover(td, type, id, field, event) { var $td = $(td); $td.find('#quickEditButton').remove(); // clean all similar if exist var $div = $('
'); $div.addClass('quick-edit-row-div'); var $span = $(''); $span.addClass('fa-as-icon fa fa-edit'); $span.css('font-size', '12px'); $div.append($span); $td.find("[id*=_solid]").append($div); $span.click(function() { activateField(type, id, field, event); }); $td.off('mouseleave').on('mouseleave', function() { $div.remove(); }); } function addSighting(type, attribute_id, event_id) { $('#Sighting_' + attribute_id + '_type').val(type); $.ajax({ data: $('#Sighting_' + attribute_id).closest("form").serialize(), cache: false, success: function (data, textStatus) { handleGenericAjaxResponse(data); var result = data; if (result.saved == true) { $('.sightingsCounter').each(function( counter ) { $(this).html(parseInt($(this).html()) + 1); }); updateIndex(event_id, 'event'); } }, error: function() { showMessage('fail', 'Request failed for an unknown reason.'); updateIndex(event_id, 'event'); }, type: "post", url: baseurl + "/sightings/add/" + attribute_id }); } function resetForms() { $('.inline-field-solid').show(); $('.inline-field-placeholder').empty(); } function inputFieldButtonActive(selector) { $(selector).closest('.inline-input-container').children('.inline-input-accept').removeClass('inline-input-passive').addClass('inline-input-active'); $(selector).closest('.inline-input-container').children('.inline-input-decline').removeClass('inline-input-passive').addClass('inline-input-active'); } function inputFieldButtonPassive(selector) { $(selector).closest('.inline-input-container').children('.inline-input-accept').addClass('inline-input-passive').removeClass('inline-input-active'); $(selector).closest('.inline-input-container').children('.inline-input-daecline').addClass('inline-input-passive').removeClass('inline-input-active'); } function autoresize(textarea) { textarea.style.height = '20px'; textarea.style.height = (textarea.scrollHeight) + 'px'; } // submit the form - this can be triggered by unfocusing the activated form field or by submitting the form (hitting enter) // after the form is submitted, intercept the response and act on it function submitForm(type, id, field, context) { var object_type = 'attributes'; var action = "editField"; var name = '#' + type + '_' + id + '_' + field; if (type == 'Object') { object_type = 'objects'; } $.ajax({ data: $(name + '_field').closest("form").serialize(), cache: false, success:function (data, textStatus) { handleAjaxEditResponse(data, name, type, id, field, context); }, error:function() { showMessage('fail', 'Request failed for an unknown reason.'); updateIndex(context, 'event'); }, type:"post", url: baseurl + "/" + object_type + "/" + action + "/" + id }); $(name + '_field').unbind("keyup"); $(name + '_form').unbind("focusout"); return false; }; function quickSubmitTagForm(selected_tag_ids, addData) { var event_id = addData.id; var localFlag = ''; if (undefined != addData['local'] && addData['local']) { localFlag = '/local:1'; } url = baseurl + "/events/addTag/" + event_id + localFlag; fetchFormDataAjax(url, function(formData) { $('body').append($('
').html(formData)); $('#temp #EventTag').val(JSON.stringify(selected_tag_ids)); $.ajax({ data: $('#EventAddTagForm').serialize(), cache: false, beforeSend: function (XMLHttpRequest) { $(".loading").show(); }, success:function (data, textStatus) { loadEventTags(event_id); loadGalaxies(event_id, 'event'); handleGenericAjaxResponse(data); }, error:function() { showMessage('fail', 'Could not add tag.'); loadEventTags(event_id); loadGalaxies(event_id, 'event'); }, complete:function() { $('#temp').remove(); $("#popover_form").fadeOut(); $("#gray_out").fadeOut(); $(".loading").hide(); $('#temp').remove(); }, type:"post", url:url }); }); } function quickSubmitAttributeTagForm(selected_tag_ids, addData) { var attribute_id = addData.id; var localFlag = ''; if (undefined != addData['local'] && addData['local']) { localFlag = '/local:1'; } url = baseurl + "/attributes/addTag/" + attribute_id + localFlag; fetchFormDataAjax(url, function(formData) { $('body').append($('
').html(formData)); $('#temp #AttributeTag').val(JSON.stringify(selected_tag_ids)); if (attribute_id == 'selected') { $('#AttributeAttributeIds').val(getSelected()); } $.ajax({ data: $('#AttributeAddTagForm').serialize(), beforeSend: function (XMLHttpRequest) { $(".loading").show(); }, success:function (data, textStatus) { if (attribute_id == 'selected') { updateIndex(0, 'event'); } else { loadAttributeTags(attribute_id); loadGalaxies(attribute_id, 'attribute'); } handleGenericAjaxResponse(data); }, error:function() { showMessage('fail', 'Could not add tag.'); loadAttributeTags(attribute_id); loadGalaxies(attribute_id, 'attribute'); }, complete:function() { $("#popover_form").fadeOut(); $("#gray_out").fadeOut(); $(".loading").hide(); $('#temp').remove(); }, type:"post", url: url }); }); } function quickSubmitTagCollectionTagForm(selected_tag_ids, addData) { var tag_collection_id = addData.id; var localFlag = ''; if (undefined != addData['local'] && addData['local']) { localFlag = '/local:1'; } url = baseurl + "/tag_collections/addTag/" + tag_collection_id + localFlag; fetchFormDataAjax(url, function(formData) { $('body').append($('
').html(formData)); $('#temp #TagCollectionTag').val(JSON.stringify(selected_tag_ids)); $.ajax({ data: $('#TagCollectionAddTagForm').serialize(), beforeSend: function (XMLHttpRequest) { $(".loading").show(); }, success:function (data, textStatus) { handleGenericAjaxResponse(data); refreshTagCollectionRow(tag_collection_id); }, error:function() { showMessage('fail', 'Could not add tag.'); loadTagCollectionTags(tag_collection_id); }, complete:function() { $("#popover_form").fadeOut(); $("#gray_out").fadeOut(); $(".loading").hide(); $('#temp').remove(); }, type:"post", url: url }); }); } function refreshTagCollectionRow(tag_collection_id) { $.ajax({ type:"get", url: baseurl + "/tag_collections/getRow/" + tag_collection_id, error:function() { showMessage('fail', 'Could not fetch updates to the modified row.'); }, success: function (data, textStatus) { $('[data-row-id="' + tag_collection_id + '"]').replaceWith(data); } }); } function handleAjaxEditResponse(data, name, type, id, field, event) { responseArray = data; if (type === 'Attribute') { if (responseArray.saved) { var msg = responseArray.success !== undefined ? responseArray.success : responseArray.message; showMessage('success', msg); updateAttributeFieldOnSuccess(name, type, id, field, event); updateAttributeFieldOnSuccess(name, type, id, 'timestamp', event); eventUnpublish(); } else { showMessage('fail', 'Validation failed: ' + responseArray.errors.value); updateAttributeFieldOnSuccess(name, type, id, field, event); } } else if (type === 'ShadowAttribute') { updateIndex(event, 'event'); } else if (type === 'Object') { if (responseArray.saved) { showMessage('success', responseArray.message); updateObjectFieldOnSuccess(name, type, id, field, event); updateObjectFieldOnSuccess(name, type, id, 'timestamp', event); eventUnpublish(); } else { showMessage('fail', 'Validation failed: ' + responseArray.errors.value); updateObjectFieldOnSuccess(name, type, id, field, event); } } if (responseArray.hasOwnProperty('check_publish')) { checkAndSetPublishedInfo(); } } function handleGenericAjaxResponse(data, skip_reload) { if (typeof skip_reload === "undefined") { skip_reload = false; } if (typeof data == 'string') { responseArray = JSON.parse(data); } else { responseArray = data; } // remove remaining popovers cancelPrompt(); // in case the origin node has been deleted (e.g. tags) $('.popover').remove(); if (responseArray.saved) { showMessage('success', responseArray.success); if (responseArray.hasOwnProperty('check_publish')) { checkAndSetPublishedInfo(skip_reload); } return true; } else { showMessage('fail', responseArray.errors); return false; } } function toggleAllAttributeCheckboxes() { if ($(".select_all").is(":checked")) { $(".select_attribute").prop("checked", true); $(".select_proposal").prop("checked", true); } else { $(".select_attribute").prop("checked", false); $(".select_proposal").prop("checked", false); } } function toggleAllCheckboxes() { if ($(".select_all").is(":checked")) { $(".select").prop("checked", true); } else { $(".select").prop("checked", false); } } function toggleAllTaxonomyCheckboxes() { if ($(".select_all").is(":checked")) { $(".select_taxonomy").prop("checked", true); } else { $(".select_taxonomy").prop("checked", false); } } function attributeListAnyAttributeCheckBoxesChecked() { if ($('.select_attribute:checked').length > 0) $('.mass-select').removeClass('hidden'); else $('.mass-select').addClass('hidden'); } function listCheckboxesChecked() { if ($('.select:checked').length > 0) $('.mass-select').removeClass('hidden'); else $('.mass-select').addClass('hidden'); } function attributeListAnyProposalCheckBoxesChecked() { if ($('.select_proposal:checked').length > 0) $('.mass-proposal-select').removeClass('hidden'); else $('.mass-proposal-select').addClass('hidden'); } function taxonomyListAnyCheckBoxesChecked() { if ($('.select_taxonomy:checked').length > 0) $('.mass-select').show(); else $('.mass-select').hide(); } function multiSelectDeleteEvents() { var selected = []; $(".select").each(function() { if ($(this).is(":checked")) { var temp = $(this).data("id"); if (temp != null) { selected.push(temp); } } }); $.get(baseurl + "/events/delete/" + JSON.stringify(selected), function(data) { $("#confirmation_box").html(data); openPopup("#confirmation_box"); }); } function multiSelectToggleFeeds(on, cache) { var selected = []; $(".select").each(function() { if ($(this).is(":checked")) { var temp = $(this).data("id"); if (temp != null) { selected.push(temp); } } }); $.get(baseurl + "/feeds/toggleSelected/" + on + "/" + cache + "/" + JSON.stringify(selected), function(data) { $("#confirmation_box").html(data); openPopup("#confirmation_box"); }); } function multiSelectDeleteEventBlocklist(on, cache) { var selected = []; $(".select").each(function() { if ($(this).is(":checked")) { var temp = $(this).data("id"); if (temp != null) { selected.push(temp); } } }); $.get(baseurl + "/eventBlocklists/massDelete?ids=" + JSON.stringify(selected), function(data) { $("#confirmation_box").html(data); openPopup("#confirmation_box"); }); } function multiSelectAction(event, context) { var settings = { deleteAttributes: { confirmation: "Are you sure you want to delete all selected attributes?", controller: "attributes", camelCase: "Attribute", alias: "attribute", action: "delete" }, acceptProposals: { confirmation: "Are you sure you want to accept all selected proposals?", controller: "shadow_attributes", camelCase: "ShadowAttribute", alias: "proposal", action: "accept" }, discardProposals: { confirmation: "Are you sure you want to discard all selected proposals?", controller: "shadow_attributes", camelCase: "ShadowAttribute", alias: "proposal", action: "discard" }, }; var answer = confirm("Are you sure you want to " + settings[context]["action"] + " all selected " + settings[context]["alias"] + "s?"); if (answer) { var selected = []; $(".select_" + settings[context]["alias"]).each(function() { if ($(this).is(":checked")) { var temp= $(this).data("id"); selected.push(temp); } }); $('#' + settings[context]["camelCase"] + 'Ids' + settings[context]["action"].ucfirst()).attr('value', JSON.stringify(selected)); var formData = $('#' + settings[context]["action"] + '_selected').serialize(); if (context == 'deleteAttributes') { var url = $('#delete_selected').attr('action'); } else { var url = baseurl + "/" + settings[context]["controller"] + "/" + settings[context]["action"] + "Selected/" + event; } $.ajax({ data: formData, cache: false, type:"POST", url: url, beforeSend: function () { $(".loading").show(); }, success: function (data) { updateIndex(event, 'event'); var result = handleGenericAjaxResponse(data); if (settings[context]["action"] != "discard" && result == true) { eventUnpublish(); } }, complete: function () { $(".loading").hide(); }, error: xhrFailCallback, }); } return false; } function editSelectedAttributes(event) { var selectedAttributeIds = getSelected(); var data = { selected_ids: selectedAttributeIds } simplePopup(baseurl + "/attributes/getMassEditForm/" + event, 'POST', data); } function addSelectedTaxonomies(taxonomy) { $.get(baseurl + "/taxonomies/taxonomyMassConfirmation/"+taxonomy, function(data) { $("#confirmation_box").html(data); openPopup("#confirmation_box"); }); } function proposeObjectsFromSelectedAttributes(clicked, event_id) { var selectedAttributeIds = getSelected(); popoverPopup(clicked, event_id + '/' + selectedAttributeIds, 'objects', 'proposeObjectsFromAttributes'); } function hideSelectedTags(taxonomy) { $.get(baseurl + "/taxonomies/taxonomyMassHide/"+taxonomy, function(data) { $("#confirmation_box").html(data); openPopup("#confirmation_box"); }); } function unhideSelectedTags(taxonomy) { $.get(baseurl + "/taxonomies/taxonomyMassUnhide/"+taxonomy, function(data) { $("#confirmation_box").html(data); openPopup("#confirmation_box"); }); } function submitMassTaxonomyTag() { $('#PromptForm').submit(); } function submitMassEventDelete() { $('#PromptForm').trigger('submit'); event.preventDefault(); } function getSelected() { var selected = []; $(".select_attribute").each(function() { if ($(this).is(":checked")) { var test = $(this).data("id"); selected.push(test); } }); return JSON.stringify(selected); } function getSelectedTaxonomyNames() { var selected = []; $(".select_taxonomy").each(function() { if ($(this).is(":checked")) { var row = $(this).data("id"); var temp = $('#tag_' + row).html(); temp = $("
").html(temp).text(); selected.push(temp); } }); $('#TaxonomyNameList').val(JSON.stringify(selected)); } function loadEventTags(id) { $.ajax({ dataType:"html", cache: false, success:function (data, textStatus) { $(".eventTagContainer").html(data); }, url: baseurl + "/tags/showEventTag/" + id, }); } function loadGalaxies(id, scope) { $.ajax({ dataType:"html", cache: false, success:function (data, textStatus) { if (scope == 'event') { $("#galaxies_div").html(data); } else if (scope == 'attribute') { $("#attribute_" + id + "_galaxy").html(data); } }, url: baseurl + "/galaxies/showGalaxies/" + id + "/" + scope, }); } function loadTagCollectionTags(id) { $.ajax({ dataType:"html", cache: false, success:function (data, textStatus) { $(".tagCollectionTagContainer").html(data); }, url: baseurl + "/tags/showEventTag/" + id, }); } function removeEventTag(event, tag) { var answer = confirm("Are you sure you want to remove this tag from the event?"); if (answer) { var formData = $('#removeTag_' + tag).serialize(); $.ajax({ beforeSend: function (XMLHttpRequest) { $(".loading").show(); }, data: formData, type:"POST", cache: false, url: baseurl + "/events/removeTag/" + event + '/' + tag, success:function (data, textStatus) { loadEventTags(event); handleGenericAjaxResponse(data); }, complete:function() { $(".loading").hide(); } }); } return false; } function loadAttributeTags(id) { $.ajax({ dataType:"html", cache: false, success:function (data, textStatus) { $("#Attribute_"+id+"_tr .attributeTagContainer").html(data); }, url: baseurl + "/tags/showAttributeTag/" + id }); } function removeObjectTagPopup(clicked, context, object, tag) { $.get(baseurl + "/" + context + "s/removeTag/" + object + '/' + tag, function(data) { openPopover(clicked, data); }); } function removeObjectTag(context, object, tag) { var formData = $('#PromptForm').serialize(); $.ajax({ beforeSend: function (XMLHttpRequest) { $(".loading").show(); }, data: formData, type:"POST", cache: false, url: baseurl + "/" + context.toLowerCase() + "s/removeTag/" + object + '/' + tag, success:function (data, textStatus) { $("#confirmation_box").fadeOut(); $("#gray_out").fadeOut(); if (context == 'Attribute') { loadAttributeTags(object); } else if (context == 'tag_collection') { refreshTagCollectionRow(object); } else { loadEventTags(object); } handleGenericAjaxResponse(data); }, complete:function() { $(".loading").hide(); } }); return false; } function redirectAddObject(templateId, additionalData) { var eventId = additionalData['event_id']; window.location = baseurl + '/objects/add/' + eventId + '/' + templateId; } function clickCreateButton(event, type) { var destination = 'attributes'; if (type == 'Proposal') destination = 'shadow_attributes'; simplePopup(baseurl + "/" + destination + "/add/" + event); } function openGenericModal(url) { $.ajax({ type: "get", url: url, success: function (data) { $('#genericModal').remove(); $('body').append(data); $('#genericModal').modal(); }, error: function (data, textStatus, errorThrown) { showMessage('fail', textStatus + ": " + errorThrown); } }); } function openGenericModalPost(url, body) { $.ajax({ data: body, type: "post", url: url, success: function (data) { $('#genericModal').remove(); $('body').append(data); $('#genericModal').modal(); }, error: function (data, textStatus, errorThrown) { showMessage('fail', textStatus + ": " + errorThrown); } }); } function submitPopoverForm(context_id, referer, update_context_id, modal, popover_dismiss_id_to_close) { var url = null; var context = 'event'; var contextNamingConvention = 'Attribute'; var closePopover = true; switch (referer) { case 'addTextElement': context = 'template'; contextNamingConvention = 'TemplateElementText'; break; case 'editTextElement': context = 'template'; context_id = update_context_id; contextNamingConvention = 'TemplateElementText'; break; case 'addAttributeElement': context = 'template'; contextNamingConvention = 'TemplateElementAttribute'; break; case 'editAttributeElement': context = 'template'; context_id = update_context_id; contextNamingConvention = 'TemplateElementAttribute'; break; case 'addFileElement': context = 'template'; contextNamingConvention = 'TemplateElementFile'; break; case 'editFileElement': context = 'template'; context_id = update_context_id; contextNamingConvention = 'TemplateElementFile'; break; case 'addSighting': closePopover = false; break; } var $submitButton = $("#submitButton"); if ($submitButton.parent().hasClass('modal-footer')) { var $form = $submitButton.parent().parent().find('.modal-body form'); url = $form.attr('action'); } else { var $form = $submitButton.closest("form"); url = $form.attr('action'); } // Prepend URL with baseurl if URL is relative if (!url.startsWith('http')) { url = baseurl + url; } $.ajax({ beforeSend: function (XMLHttpRequest) { if (modal) { if (closePopover) { $('#genericModal').modal('hide'); } } else { if (closePopover) { $("#gray_out").fadeOut(); $("#popover_form").fadeOut(); if (popover_dismiss_id_to_close !== undefined) { $('[data-dismissid="' + popover_dismiss_id_to_close + '"]').popover('destroy'); } $(".loading").show(); } } }, data: $form.serialize(), success: function (data, textStatus) { var result; if (closePopover) { if (modal) { result = handleAjaxModalResponse(data, context_id, url, referer, context, contextNamingConvention); } else { result = handleAjaxPopoverResponse(data, context_id, url, referer, context, contextNamingConvention); } } if (referer == 'addSighting') { updateIndex(update_context_id, 'event'); $.get(baseurl + "/sightings/listSightings/" + id + "/attribute", function(data) { $("#sightingsData").html(data); }); $('.sightingsToggle').removeClass('btn-primary'); $('.sightingsToggle').addClass('btn-inverse'); $('#sightingsListAllToggle').removeClass('btn-inverse'); $('#sightingsListAllToggle').addClass('btn-primary'); } if (referer == 'addEventReport' && typeof window.reloadEventReportTable === 'function') { context == 'eventReport' reloadEventReportTable() eventUnpublish() } if ( ( context == 'event' && (referer == 'add' || referer == 'massEdit' || referer == 'replaceAttributes' || referer == 'addObjectReference' || referer == 'quickAddAttributeForm') ) ){ eventUnpublish(); } }, error: function (jqXHR, textStatus, errorThrown) { showMessage('fail', textStatus + ": " + errorThrown); }, complete: function () { $(".loading").hide(); }, type: "post", url: url, }); return false; } function handleAjaxModalResponse(response, context_id, url, referer, context, contextNamingConvention) { responseArray = response; var message = null; var result = "fail"; if (responseArray.saved) { updateIndex(context_id, context); if (responseArray.success) { showMessage("success", responseArray.success); result = "success"; } if (responseArray.errors) { showMessage("fail", responseArray.errors); } } else { if (responseArray.errors) { showMessage("fail", responseArray.errors); } var savedArray = saveValuesForPersistance(); $.ajax({ async:true, dataType:"html", success:function (data, textStatus) { $('#genericModal').remove(); $('body').append(data); $('#genericModal').modal(); var error_context = context.charAt(0).toUpperCase() + context.slice(1); handleValidationErrors(responseArray.errors, context, contextNamingConvention); result = "success"; if (!$.isEmptyObject(responseArray)) { result = "fail"; } recoverValuesFromPersistance(savedArray); }, error: function (jqXHR, textStatus, errorThrown) { showMessage('fail', textStatus + ": " + errorThrown); }, complete: function () { $(".loading").hide(); }, url:url }); } return result; } function handleAjaxPopoverResponse(response, context_id, url, referer, context, contextNamingConvention) { responseArray = response; var message = null; var result = "fail"; if (responseArray.saved) { updateIndex(context_id, context); if (responseArray.success) { showMessage("success", responseArray.success); result = "success"; } if (responseArray.errors) { showMessage("fail", responseArray.errors); } } else { var savedArray = saveValuesForPersistance(); $.ajax({ async:true, dataType:"html", success:function (data, textStatus) { $("#popover_form").html(data); openPopup("#popover_form"); var error_context = context.charAt(0).toUpperCase() + context.slice(1); handleValidationErrors(responseArray.errors, context, contextNamingConvention); result = "success"; if (!$.isEmptyObject(responseArray)) { result = "fail"; $("#formWarning").show(); $("#formWarning").html('The object(s) could not be saved. Please, try again.'); } recoverValuesFromPersistance(savedArray); $(".loading").hide(); }, url:url }); } return result; } //before we update the form (in case the action failed), we want to retrieve the data from every field, so that we can set the fields in the new form that we fetch function saveValuesForPersistance() { var formPersistanceArray = new Array(); for (i = 0; i < fieldsArray.length; i++) { formPersistanceArray[fieldsArray[i]] = $('#' + fieldsArray[i]).val(); } return formPersistanceArray; } function recoverValuesFromPersistance(formPersistanceArray) { for (i = 0; i < fieldsArray.length; i++) { $('#' + fieldsArray[i]).val(formPersistanceArray[fieldsArray[i]]); } } function handleValidationErrors(responseArray, context, contextNamingConvention) { for (var k in responseArray) { var elementName = k.charAt(0).toUpperCase() + k.slice(1); $("#" + contextNamingConvention + elementName).parent().addClass("error"); $("#" + contextNamingConvention + elementName).parent().append("
" + responseArray[k] + "
"); } } function toggleHistogramType(type, old) { var done = false; old.forEach(function(entry) { if (type == entry) { done = true; old.splice(old.indexOf(entry), 1); } }); if (done == false) old.push(type); updateHistogram(JSON.stringify(old)); } function updateHistogram(selected) { $.ajax({ beforeSend: function (XMLHttpRequest) { $(".loading").show(); }, dataType:"html", cache: false, success:function (data, textStatus) { $(".loading").hide(); $("#histogram").html(data); }, url: baseurl + "/users/histogram/" + selected, }); } function showMessage(success, message, context) { if (typeof context !== "undefined") { $("#ajax_" + success, window.parent.document).html(message); var duration = 1000 + (message.length * 40); $("#ajax_" + success + "_container", window.parent.document).fadeIn("slow"); $("#ajax_" + success + "_container", window.parent.document).delay(duration).fadeOut("slow"); } $("#ajax_" + success).html(message); var duration = 1000 + (message.length * 40); $("#ajax_" + success + "_container").fadeIn("slow").delay(duration).fadeOut("slow"); } function cancelPopoverForm(id) { $("#gray_out").fadeOut(); $("#popover_form_large").fadeOut(); $("#screenshot_box").fadeOut(); $("#popover_box") .fadeOut() .removeAttr('style') // remove all inline styles .empty(); // remove all child elements $("#confirmation_box").fadeOut(); $('#popover_form').fadeOut(); if (id !== undefined && id !== '') { $(id).fadeOut(); } } function activateTagField() { $("#addTagButton").hide(); $("#addTagField").show(); } function tagFieldChange() { if ($("#addTagField :selected").val() > 0) { var selected_id = $("#addTagField :selected").val(); var selected_text = $("#addTagField :selected").text(); if ($.inArray(selected_id, selectedTags)==-1) { selectedTags.push(selected_id); appendTemplateTag(selected_id); } } $("#addTagButton").show(); $("#addTagField").hide(); } function appendTemplateTag(selected_id) { $.ajax({ beforeSend: function (XMLHttpRequest) { $(".loading").show(); }, dataType:"html", cache: false, success:function (data, textStatus) { $(".loading").hide(); $("#tags").append(data); }, url: baseurl + "/tags/viewTag/" + selected_id, }); updateSelectedTags(); } function addAllTags(tagArray) { parsedTagArray = JSON.parse(tagArray); parsedTagArray.forEach(function(tag) { appendTemplateTag(tag); }); } function removeTemplateTag(id, name) { selectedTags.forEach(function(tag) { if (tag == id) { var index = selectedTags.indexOf(id); if (index > -1) { selectedTags.splice(index, 1); updateSelectedTags(); } } }); $('#tag_bubble_' + id).remove(); } function updateSelectedTags() { $('#hiddenTags').attr("value", JSON.stringify(selectedTags)); } function saveElementSorting(order) { $.ajax({ data: order, dataType:"json", contentType: "application/json", cache: false, success:function (data, textStatus) { handleGenericAjaxResponse(data); }, type:"post", cache: false, url: baseurl + "/templates/saveElementSorting/", }); } function templateAddElementClicked(id) { simplePopup(baseurl + "/template_elements/templateElementAddChoices/" + id); } function templateAddElement(type, id) { simplePopup(baseurl + "/template_elements/add/" + type + "/" + id); } function templateUpdateAvailableTypes() { $("#innerTypes").empty(); var type = $("#TemplateElementAttributeType option:selected").text(); var complex = $('#TemplateElementAttributeComplex:checked').val(); if (complex && type != 'Select Type') { currentTypes.forEach(function(entry) { $("#innerTypes").append("
" + entry + "
"); }); $('#outerTypes').show(); } else $('#outerTypes').hide(); } function populateTemplateTypeDropdown() { var cat = $("#TemplateElementAttributeCategory option:selected").text(); currentTypes = []; if (cat == 'Select Category') { $('#TemplateElementAttributeType').html(""); } else { var complex = $('#TemplateElementAttributeComplex:checked').val(); if (cat in typeGroupCategoryMapping) { $('#TemplateElementAttributeType').html(""); typeGroupCategoryMapping[cat].forEach(function(entry) { $('#TemplateElementAttributeType').append(""); }); } else { complex = false; } if (!complex) { $('#TemplateElementAttributeType').html(""); categoryTypes[cat].forEach(function(entry) { $('#TemplateElementAttributeType').append(""); }); } } } function templateElementAttributeTypeChange() { var complex = $('#TemplateElementAttributeComplex:checked').val(); var type = $("#TemplateElementAttributeType option:selected").text(); currentTypes = []; if (type != 'Select Type') { if (complex) { complexTypes[type]["types"].forEach(function(entry) { currentTypes.push(entry); }); } else { currentTypes.push(type); } } else { currentTypes = []; } $("#typeJSON").html(JSON.stringify(currentTypes)); templateUpdateAvailableTypes(); } function templateElementAttributeCategoryChange(category) { if (category in typeGroupCategoryMapping) { $('#complexToggle').show(); } else { $('#complexToggle').hide(); } if (category != 'Select Type') { populateTemplateTypeDropdown(); } templateUpdateAvailableTypes(); } function templateElementFileCategoryChange(category) { if (category == '') { $("#TemplateElementFileMalware")[0].disabled = true; $("#TemplateElementFileMalware")[0].checked = false; } else { if (categoryArray[category].length == 2) { $("#TemplateElementFileMalware")[0].disabled = false; $("#TemplateElementFileMalware")[0].checked = true; } else { $("#TemplateElementFileMalware")[0].disabled = true; if (categoryArray[category] == 'attachment') $("#TemplateElementFileMalware")[0].checked = false; else $("#TemplateElementFileMalware")[0].checked = true; } } } function openPopup(id, adjust_layout, callback) { var $id = $(id); adjust_layout = adjust_layout === undefined ? true : adjust_layout; if (adjust_layout) { $id.css({'top': '', 'height': ''}).removeClass('vertical-scroll'); // reset inline values var window_height = $(window).height(); var popup_height = $id.height(); if (window_height < popup_height) { $id.css("top", 50); $id.css("height", window_height - 50); $id.addClass('vertical-scroll'); } else { if (window_height > (300 + popup_height)) { var top_offset = ((window_height - popup_height) / 2) - 150; } else { var top_offset = (window_height - popup_height) / 2; } $id.css("top", top_offset); } } $("#gray_out").fadeIn(); $id.fadeIn(400, function() { if (callback !== undefined) { callback(); } }); } function openPopover(clicked, data, hover, placement, callback) { hover = hover === undefined ? false : hover; placement = placement === undefined ? 'right' : placement; /* popup handling */ var $clicked = $(clicked); var randomId = $clicked.attr('data-dismissid') !== undefined ? $clicked.attr('data-dismissid') : Math.random().toString(36).substr(2,9); // used to recover the button that triggered the popover (so that we can destroy the popover) var loadingHtml = '
Loading
'; $clicked.attr('data-dismissid', randomId); var closeButtonHtml = ''; if (!$clicked.data('popover')) { $clicked.addClass('have-a-popover'); var popoverOptions = { html: true, placement: placement, trigger: 'manual', content: loadingHtml, container: 'body', template: '' }; $clicked.popover(popoverOptions) .on('shown.bs.popover', function(event) { var $this = $(this); var title = $this.attr('title'); var popover = $('div.popover[data-dismissid="' + randomId + '"]'); title = title === "" ? $this.attr('data-original-title') : title; if (title === "") { title = " "; // adjust popover position (title was empty) var top = popover.offset().top; popover.css('top', (top-17) + 'px'); } var popoverTitle = popover.find('h3.popover-title'); popoverTitle.html(title + closeButtonHtml); if (callback !== undefined) { callback(popover); } }) .on('keydown.volatilePopover', function(e) { if(e.keyCode == 27) { // ESC $(this).popover('destroy'); $(this).off('keydown.volatilePopover'); } }); if (hover) { $clicked.on('mouseenter', function() { var _this = this; $clicked.popover('show'); $(".popover").on("mouseleave", function() { // close popover when leaving it $(_this).popover('hide'); }); }) .on('mouseleave', function() { // close popover if button not hovered (timeout) var _this = this; setTimeout(function() { if ($('.popover:hover').length == 0 && !$(_this).is(":hover")) { $(_this).popover('hide'); } }, 300); }); } else { $clicked.popover('show'); } } else { $clicked.popover('show'); } var popover = $clicked.data('popover'); if (data === undefined) { return popover } else if (popover.options.content !== data) { popover.options.content = data; $clicked.popover('show'); return popover; } } function getMatrixPopup(scope, scope_id, galaxy_id) { cancelPopoverForm(); getPopup(scope_id + '/' + galaxy_id + '/' + scope, 'events', 'viewGalaxyMatrix', '', '#popover_matrix'); } function getPopup(id, context, target, admin, popupType) { $("#gray_out").fadeIn(); var url = baseurl; if (typeof admin !== 'undefined' && admin != '') url+= "/admin"; if (context != '') { url += "/" + context; } if (target != '') url += "/" + target; if (id != '') url += "/" + id; if (popupType == '' || typeof popupType == 'undefined') popupType = '#popover_form'; $.ajax({ beforeSend: function (XMLHttpRequest) { $(".loading").show(); }, dataType:"html", async: true, cache: false, success:function (data, textStatus) { $(".loading").hide(); $(popupType).html(data); openPopup(popupType, false); }, error:function(xhr) { $(".loading").hide(); $("#gray_out").fadeOut(); xhrFailCallback(xhr); }, url: url }); } // Same as getPopup function but create a popover to populate first function popoverPopup(clicked, id, context, target, admin) { var url = baseurl; if (typeof admin !== 'undefined' && admin != '') url+= "/admin"; if (context != '') { url += "/" + context; } if (target != '') url += "/" + target; if (id != '') url += "/" + id; var popover = openPopover(clicked, undefined); $clicked = $(clicked); // actual request // $.ajax({ dataType:"html", async: true, cache: false, success:function (data, textStatus) { if (popover.options.content !== data) { popover.options.content = data; $clicked.popover('show'); } }, error:function(jqXHR, textStatus, errorThrown ) { var errorJSON = ''; try { errorJSON = JSON.parse(jqXHR.responseText); errorJSON = errorJSON['errors']; if (errorJSON === undefined) { errorJSON = ''; } } catch (SyntaxError) { // no error provided } var errorText = '
Something went wrong - the queried function returned an exception. Contact your administrator for further details (the exception has been logged).
'; if (errorJSON !== '') { errorText += '
Returned error: ' + $('').text(errorJSON).html() + '
'; } popover.options.content = errorText; $clicked.popover('show'); }, url: url }); } // create a confirm popover on the clicked html node. function popoverConfirm(clicked, message, placement) { var $clicked = $(clicked); var popoverContent = '
'; popoverContent += message === undefined ? '' : '

' + message + '

'; popoverContent += ''; popoverContent += ''; popoverContent += '
'; openPopover($clicked, popoverContent, undefined, placement); $("#popoverConfirmOK") .focus() .bind("keydown", function(e) { if (e.ctrlKey && (e.keyCode == 13 || e.keyCode == 10)) { $(this).click(); } if(e.keyCode == 27) { // ESC $clicked.popover('destroy'); } }); } function submitPopover(clicked) { var $clicked = $(clicked); var $form = $clicked.closest('form'); if ($form.length === 0) { // popover container is body, submit from original node var dismissid = $clicked.closest('div.popover').attr('data-dismissid'); $form = $('[data-dismissid="' + dismissid + '"]').closest('form'); } if ($form.data('ajax')) { $.ajax({ data: $form.serialize(), beforeSend: function (XMLHttpRequest) { $(".loading").show(); }, success:function (data, textStatus) { location.reload(); }, error:function() { showMessage('fail', 'Could not perform query.'); }, complete:function() { $(".loading").hide(); $("#popover_form").fadeOut(); $("#gray_out").fadeOut(); $('#temp').remove(); }, type:"post", url: $form.attr('action') }); } else { $form.submit(); } } function simplePopup(url, requestType, data) { requestType = requestType === undefined ? 'GET' : requestType data = data === undefined ? [] : data $("#gray_out").fadeIn(); $.ajax({ beforeSend: function (XMLHttpRequest) { $(".loading").show(); }, dataType:"html", async: true, cache: false, success:function (data, textStatus) { $(".loading").hide(); $("#popover_form").html(data); openPopup("#popover_form"); }, error:function(xhr) { $(".loading").hide(); $("#gray_out").fadeOut(); xhrFailCallback(xhr); }, url: url, type: requestType, data: data }); } function choicePopup(legend, list) { var popupHtml = '
'; popupHtml += 'Select Object Category'; popupHtml += '
'; popupHtml += ''; popupHtml += ''; list.forEach(function(item) { popupHtml += ''; popupHtml += ''; popupHtml += ''; }); popupHtml += ''; popupHtml += '
'+item.text+'
'; popupHtml += '
'; popupHtml += '
Cancel
'; popupHtml += '
'; $("#popover_form").html(popupHtml); openPopup("#popover_form"); } function openModal(heading, body, footer, modal_option, css_container, css_body) { var modal_id = 'dynamic_modal_' + new Date().getTime(); var modal_html = ''; $('body').append($(modal_html)); $('#'+modal_id).modal(modal_option !== undefined ? modal_option : {}); } function resizePopoverBody() { var bodyheight = $(window).height(); bodyheight = 3 * bodyheight / 4 - 150; $("#popover_choice_main").css({"max-height": bodyheight}); } function populateTemplateHiddenFileDiv(files) { $('#TemplateFileArray').val(JSON.stringify(files)); } function populateTemplateFileBubbles() { var fileObjectArray = JSON.parse($('#TemplateFileArray').val()); fileObjectArray.forEach(function(entry) { templateAddFileBubble(entry.element_id, false, entry.filename, entry.tmp_name, 'yes'); }); } function templateFileHiddenAdd(files, element_id, batch) { var fileArray = $.parseJSON($('#TemplateFileArray', window.parent.document).val()); var contained = false; for (var j=0; j< files.length; j++) { for (var i=0; i< fileArray.length; i++) { if (fileArray[i].filename == files[j].filename) { contained = true; } if (batch == 'no' && fileArray[i].element_id == element_id) { templateDeleteFileBubble(fileArray[i].filename, fileArray[i].tmp_name, fileArray[i].element_id, 'iframe', batch); contained = false; var removeId = i; } } if (batch == 'no') fileArray.splice(removeId, 1); if (contained == false) { fileArray.push(files[j]); templateAddFileBubble(element_id, true, files[j].filename, files[j].tmp_name, batch); $('#TemplateFileArray', window.parent.document).val(JSON.stringify(fileArray)); } } } function htmlEncode(value){ return $('
').text(value).html(); } function templateAddFileBubble(element_id, iframe, filename, tmp_name, batch) { filename = htmlEncode(filename); tmp_name = htmlEncode(tmp_name); if (batch == 'no') { if (iframe == true) { $('#filenames_' + element_id, window.parent.document).html('
' + filename + 'x
'); } else { $('#filenames_' + element_id).html('
' + filename + 'x
'); } } else { if (iframe == true) { $('#filenames_' + element_id, window.parent.document).append('
' + filename + 'x
'); } else { $('#filenames_' + element_id).append('
' + filename + 'x
'); } } } function templateDeleteFileBubble(filename, tmp_name, element_id, context, batch) { $(".loading").show(); $.ajax({ type:"post", cache: false, url: baseurl + "/templates/deleteTemporaryFile/" + tmp_name, }); var c = this; if (context == 'iframe') { $('#' + tmp_name + '_container', window.parent.document).remove(); var oldArray = JSON.parse($('#TemplateFileArray', window.parent.document).val()); } else { $('#' + tmp_name + '_container').remove(); var oldArray = JSON.parse($('#TemplateFileArray').val()); } var newArray = []; oldArray.forEach(function(entry) { if (batch == 'no') { if (entry.element_id != element_id) { newArray.push(entry); } } else { if (entry.tmp_name != tmp_name) { newArray.push(entry); } } }); if (batch == 'no') { $('#fileUploadButton_' + element_id, $('#iframe_' + element_id).contents()).html('Upload File'); } if (context == 'iframe') { $('#TemplateFileArray', window.parent.document).val(JSON.stringify(newArray)); } else { $('#TemplateFileArray').val(JSON.stringify(newArray)); } $(".loading").hide(); } function templateFileUploadTriggerBrowse(id) { $('#upload_' + id + '_file').click(); } function freetextRemoveRow(id, event_id) { $('#row_' + id).hide(); $('#Attribute' + id + 'Save').attr("value", "0"); if ($(".freetext_row:visible").length == 0) { window.location = baseurl + "/events/" + event_id; } } function indexEvaluateFiltering() { if (filterContext == "event") { if (filtering.published != 2) { $('#value_published').html(publishedOptions[filtering.published]); } else { $('#value_published').html(""); } if (filtering.hasproposal != 2) { $('#value_hasproposal').html(publishedOptions[filtering.hasproposal]); } else { $('#value_hasproposal').html(""); } if (filtering.date.from != null) { var text = ""; if (filtering.date.from != "") text = "From: " + $('').text(filtering.date.from).html(); if (filtering.date.until != "") { if (text != "") text += " "; text += "Until: " + $('').text(filtering.date.until).html(); } } $('#value_date').html(text); for (var i = 0; i < simpleFilters.length; i++) { indexEvaluateSimpleFiltering(simpleFilters[i]); } indexRuleChange(); } else { for (var i = 0; i < differentFilters.length; i++) { if (filtering[differentFilters[i]] != "") { var text = ""; if (filtering[differentFilters[i]] == 1) text = "Yes"; else if (filtering[differentFilters[i]] == 0) text = "No"; $('#value_' + differentFilters[i]).text(text); } else { $('#value_' + differentFilters[i]).text(""); } } for (var i = 0; i < simpleFilters.length; i++) { indexEvaluateSimpleFiltering(simpleFilters[i]); } } indexSetTableVisibility(); indexSetRowVisibility(); $('#generatedURLContent').text(indexCreateFilters()); } function quickFilter(passedArgs, url) { if(!passedArgs){ var passedArgs = []; } if( $('#quickFilterField').val().trim().length > 0){ passedArgs["searchall"] = encodeURIComponent($('#quickFilterField').val().trim()); for (var key in passedArgs) { if (key !== 'page') { url += "/" + key + ":" + passedArgs[key]; } } } window.location.href=url; } function runIndexFilter(element) { var dataFields = $(element).data(); for (var k in $(element).data()) { if (k in passedArgsArray) { delete(passedArgsArray[k]); } else { passedArgsArray[k] = dataFields[k]; } } url = here; for (var key in passedArgsArray) { url += "/" + key + ":" + passedArgsArray[key]; } window.location.href = url; } function runIndexQuickFilter(preserveParams) { if (!passedArgsArray) { var passedArgsArray = []; } var searchKey = 'searchall'; if ($('#quickFilterField').data('searchkey')) { searchKey = $('#quickFilterField').data('searchkey'); } if ( $('#quickFilterField').val().trim().length > 0){ passedArgsArray[searchKey] = encodeURIComponent($('#quickFilterField').val().trim()); } url = here; if (typeof preserveParams !== "undefined") { url += preserveParams; } for (var key in passedArgsArray) { if (key !== 'page') { url += "/" + key + ":" + passedArgsArray[key]; } } window.location.href = url; } function executeFilter(passedArgs, url) { for (var key in passedArgs) url += "/" + key + ":" + passedArgs[key]; window.location.href=url; } function quickFilterTaxonomy(taxonomy_id, passedArgs) { var url = baseurl + "/taxonomies/view/" + taxonomy_id + "/filter:" + encodeURIComponent($('#quickFilterField').val()); window.location.href=url; } function quickFilterRemoteEvents(passedArgs, id) { passedArgs["searchall"] = $('#quickFilterField').val(); var url = baseurl + "/servers/previewIndex/" + id; for (var key in passedArgs) { url += "/" + key + ":" + encodeURIComponent(passedArgs[key]); } window.location.href=url; } function remoteIndexApplyFilters() { var url = actionUrl + '/' + $("#EventFilter").val(); window.location.href = url; } function indexApplyFilters() { var url = indexCreateFilters(); window.location.href = url; } function indexCreateFilters() { text = ""; if (filterContext == 'event') { if (filtering.published != "2") { text += "searchpublished:" + filtering.published; } if (filtering.hasproposal != "2") { if (text != "") text += "/"; text += "searchhasproposal:" + filtering.hasproposal; } } else { for (var i = 0; i < differentFilters.length; i++) { if (filtering[differentFilters[i]]) { if (text != "") text += "/"; text += "search" + differentFilters[i] + ":" + filtering[differentFilters[i]]; } } } for (var i = 0; i < simpleFilters.length; i++) { text = indexBuildArray(simpleFilters[i], text); } if (filterContext == 'event') { if (filtering.date.from) { if (text != "") text += "/"; text += "searchDatefrom:" + filtering.date.from; } if (filtering.date.until) { if (text != "") text += "/"; text += "searchDateuntil:" + filtering.date.until; } return baseurl + '/events/index/' + text; } else { return baseurl + '/admin/users/index/' + text; } } function indexBuildArray(type, text) { temp = ""; if (text != "") temp += "/"; temp += "search" + type + ":"; if (filtering[type].NOT.length == 0 && filtering[type].OR.length == 0) return text; var swap = filtering[type].OR.length; var temp_array = filtering[type].OR.concat(filtering[type].NOT); for (var i = 0; i < temp_array.length; i++) { if (i > 0) temp += "|"; if (i >= swap) temp +="!"; temp += temp_array[i]; } text += temp; return text; } function indexSetRowVisibility() { for (var i = 0; i < allFields.length; i++) { if ($("#value_" + allFields[i]).text().trim() != "") { $("#row_" + allFields[i]).show(); } else { $("#row_" + allFields[i]).hide(); } } } function indexEvaluateSimpleFiltering(field) { text = ""; if (filtering[field].OR.length == 0 && filtering[field].NOT.length == 0) { $('#value_' + field).html(text); return false; } if (filtering[field].OR.length !=0) { for (var i = 0; i < filtering[field].OR.length; i++) { if (i > 0) text += ' OR '; if (typedFields.indexOf(field) == -1) { text += $('').text(filtering[field].OR[i]).html(); } else { for (var j = 0; j < typeArray[field].length; j++) { if (typeArray[field][j].id == filtering[field].OR[i]) { text += $('').text(typeArray[field][j].value).html(); } } } } } if (filtering[field].NOT.length !=0) { for (var i = 0; i < filtering[field].NOT.length; i++) { if (i == 0) { if (text != "") text += ' AND NOT '; else text += 'NOT '; } else text += ' AND NOT '; if (typedFields.indexOf(field) == -1) { text += $('').text(filtering[field].NOT[i]).html(); } else { for (var j = 0; j < typeArray[field].length; j++) { if (typeArray[field][j].id == filtering[field].NOT[i]) { text += $('').text(typeArray[field][j].value).html(); } } } } } $('#value_' + field).html(text); } function indexAddRule(param) { var found = false; if (filterContext == 'event') { if (param.data.param1 == "date") { var val1 = encodeURIComponent($('#EventSearch' + param.data.param1 + 'from').val()); var val2 = encodeURIComponent($('#EventSearch' + param.data.param1 + 'until').val()); if (val1 != "") filtering.date.from = val1; if (val2 != "") filtering.date.until = val2; } else if (param.data.param1 == "published") { var value = encodeURIComponent($('#EventSearchpublished').val()); if (value != "") filtering.published = value; } else if (param.data.param1 == "hasproposal") { var value = encodeURIComponent($('#EventSearchhasproposal').val()); if (value != "") filtering.hasproposal = value; } else { var value = encodeURIComponent($('#EventSearch' + param.data.param1).val()); var operator = operators[encodeURIComponent($('#EventSearchbool').val())]; if (value != "" && filtering[param.data.param1][operator].indexOf(value) < 0) filtering[param.data.param1][operator].push(value); } } else if (filterContext == 'user') { if (differentFilters.indexOf(param.data.param1) != -1) { var value = encodeURIComponent($('#UserSearch' + param.data.param1).val()); if (value != "") filtering[param.data.param1] = value; } else { var value = encodeURIComponent($('#UserSearch' + param.data.param1).val()); var operator = operators[encodeURIComponent($('#UserSearchbool').val())]; if (value != "" && filtering[param.data.param1][operator].indexOf(value) < 0) filtering[param.data.param1][operator].push(value); } } indexEvaluateFiltering(); } function indexSetTableVisibility() { var visible = false; if ($("[id^='value_']").text().trim()!="" && $("[id^='value_']").text().trim()!="-1") { visible = true; } if (visible == true) $('#FilterplaceholderTable').hide(); else $('#FilterplaceholderTable').show(); } function indexRuleChange() { var context = filterContext.charAt(0).toUpperCase() + filterContext.slice(1); $('[id^=' + context + 'Search]').hide(); var rule = $('#' + context + 'Rule').val(); var fieldName = '#' + context + 'Search' + rule; if (fieldName == '#' + context + 'Searchdate') { $(fieldName + 'from').show(); $(fieldName + 'until').show(); } else { $(fieldName).show(); } if (simpleFilters.indexOf(rule) != -1) { $('#' + context + 'Searchbool').show(); } else $('#' + context + 'Searchbool').hide(); $('#addRuleButton').show(); $('#addRuleButton').unbind("click"); $('#addRuleButton').click({param1: rule}, indexAddRule); } function indexFilterClearRow(field) { $('#value_' + field).html(""); $('#row_' + field).hide(); if (field == "date") { filtering.date.from = ""; filtering.date.until = ""; } else if (field == "published") { filtering.published = 2; } else if (field == "hasproposal") { filtering.hasproposal = 2; } else if (differentFilters.indexOf(field) != -1) { filtering[field] = ""; } else { filtering[field].NOT = []; filtering[field].OR = []; } indexSetTableVisibility(); indexEvaluateFiltering(); } function restrictEventViewPagination() { var showPages = new Array(); var start; var end; var i; if (page < 6) { start = 1; if (count - page < 6) { end = count; } else { end = page + (9 - (page - start)); } } else if (count - page < 6) { end = count; start = count - 10; } else { start = page-5; end = page+5; } if (start > 2) { $("#apage" + start).parent().before("
  • ...
  • "); $("#aExpandLeft").click(function() {expandPagination(0, 0); return false;}); $("#bpage" + start).parent().before("
  • ...
  • "); $("#bExpandLeft").click(function() {expandPagination(1, 0); return false;}) } if (end < (count - 1)) { $("#apage" + end).parent().after("
  • ...
  • "); $("#aExpandRight").click(function() {expandPagination(0, 1); return false;}); $("#bpage" + end).parent().after("
  • ...
  • "); $("#bExpandRight").click(function() {expandPagination(1, 1); return false;}) } for (i = 1; i < (count+1); i++) { if (i != 1 && i != count && (i < start || i > end)) { $("#apage" + i).hide(); $("#bpage" + i).hide(); } } } function expandPagination(bottom, right) { var i; var prefix = "a"; if (bottom == 1) prefix = "b"; var start = 1; var end = page; if (right == 1) { start = page; end = count; $("#" + prefix + "ExpandRight").remove(); } else $("#" + prefix + "ExpandLeft").remove(); for (i = start; i < end; i++) { $("#" + prefix + "page" + i).show(); } } function getSubGroupFromSetting(setting) { var temp = setting.split('.'); if (temp[0] == "Plugin") { temp = temp[1]; if (temp.indexOf('_') > -1) { temp = temp.split('_'); return temp[0]; } } return 'general'; } function serverSettingsActivateField(setting, id) { resetForms(); $('.inline-field-placeholder').hide(); var fieldName = "#setting_" + getSubGroupFromSetting(setting) + "_" + id; $.ajax({ beforeSend: function (XMLHttpRequest) { $(".loading").show(); }, dataType:"html", cache: false, success:function (data, textStatus) { $(".loading").hide(); $(fieldName + "_placeholder").html(data); $(fieldName + "_solid").hide(); $(fieldName + "_placeholder").show(); serverSettingsPostActivationScripts(fieldName, setting, id); }, url: baseurl + "/servers/serverSettingsEdit/" + setting + "/" + id, }); } function serverSettingsPostActivationScripts(name, setting, id) { $(name + '_field').focus(); inputFieldButtonActive(name + '_field'); $(name + '_form').submit(function(e){ e.preventDefault(); serverSettingSubmitForm(name, setting, id); return false; }); $(name + '_form').bind("focusout", function() { inputFieldButtonPassive(name + '_field'); }); $(name + '_form').bind("focusin", function(){ inputFieldButtonActive(name + '_field'); }); $(name + '_form').bind("keydown", function(e) { if (e.ctrlKey && (e.keyCode == 13 || e.keyCode == 10)) { serverSettingSubmitForm(name, setting, id); } }); $(name + '_field').closest('.inline-input-container').children('.inline-input-accept').bind('click', function() { serverSettingSubmitForm(name, setting, id); }); $(name + '_field').closest('.inline-input-container').children('.inline-input-decline').bind('click', function() { resetForms(); $('.inline-field-placeholder').hide(); }); $(name + '_solid').hide(); } function serverSettingSubmitForm(name, setting, id) { var subGroup = getSubGroupFromSetting(setting); var formData = $(name + '_field').closest("form").serialize(); $.ajax({ data: formData, cache: false, beforeSend: function () { $(".loading").show(); }, success: function (data) { if (!data.saved) { $(".loading").hide(); showMessage('fail', data.errors); resetForms(); $('.inline-field-placeholder').hide(); return; } $.ajax({ type: "get", url: baseurl + "/servers/serverSettingsReloadSetting/" + setting + "/" + id, success: function (data2) { $('#' + subGroup + "_" + id + '_row').replaceWith(data2); $(".loading").hide(); }, error: function() { showMessage('fail', 'Could not refresh the table.'); } }); }, error: function() { $(".loading").hide(); showMessage('fail', 'Request failed for an unknown reason.'); resetForms(); $('.inline-field-placeholder').hide(); }, type: "post", url: baseurl + "/servers/serverSettingsEdit/" + setting + "/" + id + "/" + 1 }); $(name + '_field').unbind("keyup"); $(name + '_form').unbind("focusout"); return false; } function updateOrgCreateImageField(string) { string = encodeURIComponent(string); $.ajax({ url: baseurl + '/img/orgs/' + string + '.png', type:'HEAD', error: function(){ $('#logoDiv').html('No image uploaded for this identifier'); }, success: function(){ $('#logoDiv').html(''); } }); } function generateOrgUUID() { $.ajax({ url: baseurl + '/admin/organisations/generateuuid.json', success: function( data ){ $('#OrganisationUuid').val(data.uuid); } }); } function sharingGroupIndexMembersCollapse(id) { $('#' + id + '_down').show(); $('#' + id + '_up').hide(); } function sharingGroupIndexMembersExpand(id) { $('#' + id + '_down').hide(); $('#' + id + '_up').show(); } function popoverStartup() { $('[data-toggle="popover"]').popover({ animation: true, html: true, }).click(function(e) { $(e.target).popover('show'); $('[data-toggle="popover"]').not(e.target).popover('hide'); }); $(document).click(function (e) { if (!$('[data-toggle="popover"]').is(e.target)) { $('[data-toggle="popover"]').popover('hide'); } }); } function changeFreetextImportFrom() { $('#changeTo').find('option').remove(); options[$('#changeFrom').val()].forEach(function(element) { $('#changeTo').append(''); }); } function changeFreetextImportCommentExecute() { $('.freetextCommentField').val($('#changeComments').val()); } function changeFreetextImportExecute() { var from = $('#changeFrom').val(); var to = $('#changeTo').val(); $('.typeToggle').each(function() { if ($( this ).val() == from) { if (selectContainsOption("#" + $(this).attr('id'), to)) $( this ).val(to); } }); } function selectContainsOption(selectid, value) { var exists = false; $(selectid + ' option').each(function(){ if (this.value == value) { exists = true; return false; } }); return exists; } function exportChoiceSelect(e) { if ($(e.target).is("input")) { return false; } var url = $(e.target).parent().data("export-url"); var elementId = $(e.target).parent().data("export-key"); var checkbox = $(e.target).parent().data("export-checkbox"); if (checkbox == 1) { if ($('#' + elementId + '_toggle').prop('checked')) { url = $('#' + elementId + '_set').html(); } } document.location.href = url; } function importChoiceSelect(url, elementId, ajax) { if (ajax == 'false') { document.location.href = url; } else { simplePopup(url); } } function freetextImportResultsSubmit(id, count) { var attributeArray = []; var temp; for (var i = 0; i < count; i++) { if ($('#Attribute' + i + 'Save').val() == 1) { temp = { value:$('#Attribute' + i + 'Value').val(), category:$('#Attribute' + i + 'Category').val(), type:$('#Attribute' + i + 'Type').val(), to_ids:$('#Attribute' + i + 'To_ids')[0].checked, disable_correlation:$('#Attribute' + i + 'Disable_correlation')[0].checked, comment:$('#Attribute' + i + 'Comment').val(), distribution:$('#Attribute' + i + 'Distribution').val(), sharing_group_id:$('#Attribute' + i + 'SharingGroupId').val(), data:$('#Attribute' + i + 'Data').val(), data_is_handled:$('#Attribute' + i + 'DataIsHandled').val(), tags:$('#Attribute' + i + 'Tags').val() } attributeArray[attributeArray.length] = temp; } } $("#AttributeJsonObject").val(JSON.stringify(attributeArray)); var formData = $(".mainForm").serialize(); $.ajax({ type: "post", cache: false, url: baseurl + "/events/saveFreeText/" + id, data: formData, beforeSend: function () { $(".loading").show(); }, success: function () { window.location = baseurl + '/events/view/' + id; }, complete: function() { $(".loading").hide(); }, error: xhrFailCallback, }); } function moduleResultsSubmit(id) { var typesWithData = ['attachment', 'malware-sample']; var data_collected = {}; var temp; if ($('.meta_table').length) { var tags = []; $('.meta_table').find('.tag').each(function() { tags.push({name: $(this).text()}); }); if (tags.length) { data_collected['Tag'] = tags; } } if ($('.MISPObject').length) { var objects = []; $(".MISPObject").each(function(o) { var object_uuid = $(this).find('.ObjectUUID').text(); temp = { uuid: object_uuid, import_object: $(this).find('.ImportMISPObject')[0].checked, name: $(this).find('.ObjectName').text(), meta_category: $(this).find('.ObjectMetaCategory').text(), distribution: $(this).find('.ObjectDistribution').val(), sharing_group_id: $(this).find('.ObjectSharingGroup').val(), comment: $(this).find('.ObjectComment').val() } if (!temp['import_object']) { return true; } if (temp['distribution'] != '4') { temp['sharing_group_id'] = '0'; } if ($(this).has('.ObjectID').length) { temp['id'] = $(this).find('.ObjectID').text(); } if ($(this).has('.ObjectDescription').length) { temp['description'] = $(this).find('.ObjectDescription').text(); } if ($(this).has('.TemplateVersion').length) { temp['template_version'] = $(this).find('.TemplateVersion').text(); } if ($(this).has('.TemplateUUID').length) { temp['template_uuid'] = $(this).find('.TemplateUUID').text(); } if ($(this).has('.ObjectReference').length) { var references = []; $(this).find('.ObjectReference').each(function() { var reference = { object_uuid: object_uuid, referenced_uuid: $(this).find('.ReferencedUUID').text(), relationship_type: $(this).find('.Relationship').text() }; references.push(reference); }); temp['ObjectReference'] = references; } if ($(this).find('.ObjectAttribute').length) { var object_attributes = []; $(this).find('.ObjectAttribute').each(function(a) { var attribute_type = $(this).find('.AttributeType').text(); attribute = { import_attribute: $(this).find('.ImportMISPObjectAttribute')[0].checked, object_relation: $(this).find('.ObjectRelation').text(), category: $(this).find('.AttributeCategory').text(), type: attribute_type, value: $(this).find('.AttributeValue').text(), uuid: $(this).find('.AttributeUuid').text(), to_ids: $(this).find('.AttributeToIds')[0].checked, disable_correlation: $(this).find('.AttributeDisableCorrelation')[0].checked, comment: $(this).find('.AttributeComment').val(), distribution: $(this).find('.AttributeDistribution').val(), sharing_group_id: $(this).find('.AttributeSharingGroup').val() } if (!attribute['import_attribute']) { return true; } if (attribute['distribution'] != '4') { attribute['sharing_group_id'] = '0'; } if ($(this).find('.objectAttributeTagContainer').length) { var tags = []; $(this).find('.objectAttributeTag').each(function() { tags.push({ name: $(this).attr('title'), colour: rgb2hex($(this).css('background-color')) }); }); attribute['Tag'] = tags; } if (typesWithData.indexOf(attribute_type) != -1) { if ($(this).find('.AttributeData').length) { attribute['data'] = $(this).find('.AttributeData').val(); } if ($(this).find('.AttributeEncrypt').length) { attribute['encrypt'] = $(this).find('.AttributeEncrypt').val(); } } object_attributes.push(attribute); }); temp['Attribute'] = object_attributes; } objects.push(temp); }); data_collected['Object'] = objects; } if ($('.MISPAttribute').length) { var attributes = []; $('.MISPAttribute').each(function() { var category_value; var type_value; if ($(this).find('.AttributeCategorySelect').length) { category_value = $(this).find('.AttributeCategorySelect').val(); } else { category_value = $(this).find('.AttributeCategory').text(); } if ($(this).find('.AttributeTypeSelect').length) { type_value = $(this).find('.AttributeTypeSelect').val(); } else { type_value = $(this).find('.AttributeType').text(); } temp = { import_attribute: $(this).find('.ImportMISPAttribute')[0].checked, category: category_value, type: type_value, value: $(this).find('.AttributeValue').text(), uuid: $(this).find('.AttributeUuid').text(), to_ids: $(this).find('.AttributeToIds')[0].checked, disable_correlation: $(this).find('.AttributeDisableCorrelation')[0].checked, comment: $(this).find('.AttributeComment').val(), distribution: $(this).find('.AttributeDistribution').val(), sharing_group_id: $(this).find('.AttributeSharingGroup').val() } if (!temp['import_attribute']) { return true; } if (temp['distribution'] != '4') { temp['sharing_group_id'] = '0'; } if ($(this).find('.attributeTagContainer').length) { var tags = []; $(this).find('.attributeTag').each(function() { tags.push({ name: $(this).attr('title'), colour: rgb2hex($(this).css('background-color')) }); }); temp['Tag'] = tags; } if (typesWithData.indexOf(type_value) != -1) { if ($(this).find('.AttributeData').length) { temp['data'] = $(this).find('.AttributeData').val(); } if ($(this).find('.AttributeEncrypt').length) { temp['encrypt'] = $(this).find('.AttributeEncrypt').val(); } } attributes.push(temp); }); data_collected['Attribute'] = attributes; } $("#EventJsonObject").val(JSON.stringify(data_collected)); var formData = $('.mainForm').serialize(); $.ajax({ type: "post", cache: false, url: baseurl + "/events/handleModuleResults/" + id, data: formData, beforeSend: function () { $(".loading").show(); }, success: function () { window.location = baseurl + '/events/view/' + id; }, complete: function() { $(".loading").hide(); }, error: xhrFailCallback, }); } function objectTemplateViewContent(context, id) { var url = baseurl + "/objectTemplateElements/viewElements/" + id + "/" + context; $.ajax({ url: url, type:'GET', beforeSend: function (XMLHttpRequest) { $(".loading").show(); }, error: function(){ $('#ajaxContent').html('An error has occured, please reload the page.'); }, success: function(response){ $('#ajaxContent').html(response); }, complete: function() { $(".loading").hide(); }, }); } function organisationViewContent(context, id) { organisationViewButtonHighlight(context); var action; if (context === 'members') { action = "/admin/users/index/searchorg:"; } else if (context === 'events') { action = "/events/index/searchorg:"; } $.ajax({ url: baseurl + action + id, type:'GET', beforeSend: function () { $(".loading").show(); }, error: function(){ $('#ajaxContent').html('An error has occured, please reload the page.'); }, success: function(response){ $('#ajaxContent').html(response); }, complete: function() { $(".loading").hide(); }, }); } function organisationViewButtonHighlight(context) { $(".orgViewButtonActive").hide(); $(".orgViewButton").show(); $("#button_" + context).hide(); $("#button_" + context + "_active").show(); } function simpleTabPage(page) { $(".progress_tab").removeClass("btn-primary").addClass("btn-inverse"); $("#page" + page + "_tab").removeClass("btn-inverse").addClass("btn-primary"); $(".tabContent").hide(); $("#page" + page + "_content").show(); if (page == lastPage) simpleTabPageLast(); } function simpleTabPageLast() { var summaryorgs = summaryextendorgs = remotesummaryorgs = remotesummaryextendorgs = summaryservers = ""; var orgcounter = extendcounter = remoteorgcounter = remoteextendcounter = servercounter = 0; var sgname = "[Sharing group name not set!]"; if ($('#SharingGroupName').val()) sgname = $('#SharingGroupName').val(); var sgreleasability = "[Sharing group releasability not set!]"; if ($('#SharingGroupReleasability').val()) sgreleasability = $('#SharingGroupReleasability').val(); $('#summarytitle').text(sgname); $('#summaryreleasable').text(sgreleasability); organisations.forEach(function(organisation){ if (organisation.type == 'local') { if (orgcounter > 0) summaryorgs += ", "; summaryorgs += organisation.name; if (organisation.extend == true) { if (extendcounter > 0) summaryextendorgs += ", " summaryextendorgs += organisation.name; extendcounter++; } orgcounter++; } else { if (remoteorgcounter > 0) remotesummaryorgs += ", "; remotesummaryorgs += organisation.name; if (organisation.extend == true) { if (remoteextendcounter > 0) remotesummaryextendorgs += ", " remotesummaryextendorgs += organisation.name; remoteextendcounter++; } remoteorgcounter++; } }); if (orgcounter == 0) $('#localText').hide(); if (remoteorgcounter == 0) $('#externalText').hide(); if (extendcounter == 0) summaryextendorgs = "nobody"; if (remoteextendcounter == 0) remotesummaryextendorgs = "nobody"; servers.forEach(function(server){ if (servercounter > 0) summaryservers += ", "; if (server.id != 0) { summaryservers += server.name; if (extendcounter == 0) summaryextendorgs = "none"; servercounter++; } if (server.id == 0 && server.all_orgs == true) summaryorgs = "all organisations on this instance"; }); if ($('#SharingGroupRoaming').is(":checked")) { summaryservers = "any interconnected instances linked by an eligible organisation."; } else { if (servercounter == 0) { summaryservers = "data marked with this sharing group will not be pushed."; } } $('#summarylocal').text(summaryorgs); $('#summarylocalextend').text(summaryextendorgs); $('#summaryexternal').text(remotesummaryorgs); $('#summaryexternalextend').text(remotesummaryextendorgs); $('#summaryservers').text(summaryservers); } function sharingGroupPopulateOrganisations() { $('input[id=SharingGroupOrganisations]').val(JSON.stringify(organisations)); $('.orgRow').remove(); var id = 0; var html = ''; organisations.forEach(function(org) { html = ''; html += '' + org.type + ' '; html += '' + $('
    ').text(org.name).html() + ' '; html += '' + org.uuid + ' '; html += ''; if (org.removable == 1) { html += ''; html += ' '; $('#organisations_table tr:last').after(html); id++; }); } function sharingGroupPopulateServers() { $('input[id=SharingGroupServers]').val(JSON.stringify(servers)); $('.serverRow').remove(); var id = 0; var html = ''; servers.forEach(function(server) { html = ''; html += '' + server.name + ' '; html += '' + server.url + ' '; html += ''; html += ''; html += ' '; $('#servers_table tr:last').after(html); id++; }); } function sharingGroupExtendOrg(id) { organisations[id].extend = $('#orgExtend' + id).is(":checked"); } function sharingGroupServerAddOrgs(id) { servers[id].all_orgs = $('#serverAddOrgs' + id).is(":checked"); } function sharingGroupPopulateUsers() { $('input[id=SharingGroupServers]').val(JSON.stringify(organisations)); } function sharingGroupAdd(context, type) { if (context == 'organisation') { var jsonids = JSON.stringify(orgids); url = baseurl + '/organisations/fetchOrgsForSG/' + jsonids + '/' + type } else if (context == 'server') { var jsonids = JSON.stringify(serverids); url = baseurl + '/servers/fetchServersForSG/' + jsonids } $("#gray_out").fadeIn(); simplePopup(url); } function sharingGroupRemoveOrganisation(id) { organisations.splice(id, 1); orgids.splice(id, 1); sharingGroupPopulateOrganisations(); } function sharingGroupRemoveServer(id) { servers.splice(id, 1); serverids.splice(id, 1); sharingGroupPopulateServers(); } function submitPicklistValues(context, local) { if (context == 'org') { var localType = 'local'; if (local == 0) localType = 'remote'; $("#rightValues option").each(function() { if (orgids.indexOf($(this).val()) == -1) { organisations.push({ id: $(this).val(), type: localType, name: $(this).text(), extend: false, uuid: '', removable: 1 }); } orgids.push($(this).val()); sharingGroupPopulateOrganisations(); }); } else if (context == 'server') { $("#rightValues option").each(function() { if (serverids.indexOf($(this).val()) == -1) { servers.push({ id: $(this).val(), name: $(this).text(), url: $(this).attr("data-url"), all_orgs: false, removable: 1 }); } serverids.push($(this).val()); sharingGroupPopulateServers(); }); } $("#gray_out").fadeOut(); $("#popover_form").fadeOut(); } function cancelPicklistValues() { $("#popover_form").fadeOut(); $("#gray_out").fadeOut(); } function sgSubmitForm(action) { var ajax = { 'organisations': organisations, 'servers': servers, 'sharingGroup': { 'name': $('#SharingGroupName').val(), 'releasability': $('#SharingGroupReleasability').val(), 'description': $('#SharingGroupDescription').val(), 'active': $('#SharingGroupActive').is(":checked"), 'roaming': $('#SharingGroupRoaming').is(":checked"), } }; $('#SharingGroupJson').val(JSON.stringify(ajax)); var formName = "#SharingGroup" + action + "Form"; $(formName).submit(); } function serverSubmitForm(action) { var ajax = {}; switch ($('#ServerOrganisationType').val()) { case '0': ajax = { 'id': $('#ServerLocal').val() }; break; case '1': ajax = { 'id': $('#ServerExternal').val() }; break; case '2': ajax = { 'name': $('#ServerExternalName').val(), 'uuid': $('#ServerExternalUuid').val() }; break; } $('#ServerJson').val(JSON.stringify(ajax)); var formName = "#Server" + action + "Form"; $(formName).submit(); } function serverOrgTypeChange() { $(".hiddenField").hide(); switch ($('#ServerOrganisationType').val()) { case '0': $("#ServerLocalContainer").show(); break; case '1': $("#ServerExternalContainer").show(); break; case '2': $("#ServerExternalUuidContainer").show(); $("#ServerExternalNameContainer").show(); break; } } function sharingGroupPopulateFromJson() { var jsonparsed = JSON.parse($('#SharingGroupJson').val()); organisations = jsonparsed.organisations; servers = jsonparsed.servers; if (jsonparsed.sharingGroup.active == 1) { $("#SharingGroupActive").prop("checked", true); } if (jsonparsed.sharingGroup.roaming == 1) { $("#SharingGroupRoaming").prop("checked", true); $('#serverList').show(); } $('#SharingGroupName').attr('value', jsonparsed.sharingGroup.name); $('#SharingGroupReleasability').attr('value', jsonparsed.sharingGroup.releasability); $('#SharingGroupDescription').text(jsonparsed.sharingGroup.description); } function runOnDemandAction(element, url, target, postFormField) { var elementContainer = '#' + target; var type = 'GET'; var data = ''; if (postFormField !== '') { type = 'POST'; data = $('#' + postFormField).val(); data = {value: data} } $.ajax({ url: url, type: type, data: data, beforeSend: function (XMLHttpRequest) { $(elementContainer).html('Running...'); }, error: function(response) { var result = JSON.parse(response.responseText); $(elementContainer).empty(); $(elementContainer) .append( $('
    ') .attr('class', 'bold red') .text('Error ' + response.status + ':') ) .append( $('
    ') .attr('class', 'bold') .text(result.errors) ); }, success: function(response) { var result = JSON.parse(response); $(elementContainer).empty(); for (var key in result) { $(elementContainer).append( $('
    ') .append( $('') .attr('class', 'bold') .text(key + ': ') ).append( $('') .attr('class', 'bold blue') .text(result[key]) ) ); } } }) } function getRemoteSyncUser(id) { var resultContainer = $("#sync_user_test_" + id); $.ajax({ url: baseurl + '/servers/getRemoteUser/' + id, type:'GET', beforeSend: function (XMLHttpRequest) { resultContainer.html('Running test...'); }, error: function(){ resultContainer.html('Internal error.'); }, success: function(response) { if (typeof(response.message) != 'undefined') { resultContainer.empty(); resultContainer.append( $('') .attr('class', 'red bold') .text('Error') ).append( $('') .text(': #' + response.message) ); } else { resultContainer.empty(); Object.keys(response).forEach(function(key) { var value = response[key]; resultContainer.append( $('') .attr('class', 'blue bold') .text(key) ).append( $('') .text(': ' + value) ).append( $('
    ') ); }); } var result = response; } }); } function testConnection(id) { $.ajax({ url: baseurl + '/servers/testConnection/' + id, type: 'GET', beforeSend: function () { $("#connection_test_" + id).html('Running test...'); }, error: function(){ $("#connection_test_" + id).html('Internal error'); }, success: function(result) { function line(name, value, valid) { var $value = $('').text(value); if (valid === true) { $value.addClass('green'); } else if (valid === false) { $value.addClass('red'); } else if (valid) { $value.addClass(valid); } return $('
    ').text(name + ': ').append($value).html() + '
    '; } var html = ''; if (result.client_certificate) { var cert = result.client_certificate; html += 'Client certificate:
    '; if (cert.error) { html += 'Error: ' + cert.error + '
    '; } else { html += line("Subject", cert.subject); html += line("Issuer", cert.issuer); html += line("Serial number", cert.serial_number); html += line("Valid from", cert.valid_from, cert.valid_from_ok); html += line("Valid to", cert.valid_to, cert.valid_to_ok); html += line("Public key", cert.public_key_type + ' (' + cert.public_key_size + ' bits)', cert.public_key_size_ok); } html += "
    "; } switch (result.status) { case 1: var status_message = "OK"; var compatibility = "Compatible"; var compatibility_colour = "green"; var colours = {'local': 'class="green"', 'remote': 'class="green"', 'status': 'class="green"'}; var issue_colour = "red"; if (result.mismatch == "hotfix") issue_colour = "orange"; if (result.newer == "local") { colours.remote = 'class="' + issue_colour + '"'; if (result.mismatch == "minor") { compatibility = "Pull only"; compatibility_colour = "orange"; } else if (result.mismatch == "major") { compatibility = "Incompatible"; compatibility_colour = "red"; } } else if (result.newer == "remote") { colours.local = 'class="' + issue_colour + '"'; if (result.mismatch != "hotfix") { compatibility = "Incompatible"; compatibility_colour = "red"; } } else if (result.mismatch == "proposal") { compatibility_colour = "orange"; compatibility = "Proposal pull disabled (remote version < v2.4.111)"; } if (result.mismatch != false && result.mismatch != "proposal") { if (result.newer == "remote") status_message = "Local instance outdated, update!"; else status_message = "Remote outdated, notify admin!" colours.status = 'class="' + issue_colour + '"'; } var post_result; if (result.post != false) { var post_colour = "red"; if (result.post == 1) { post_colour = "green"; post_result = "Received sent package"; } else if (result.post == 8) { post_result = "Could not POST message"; } else if (result.post == 9) { post_result = "Invalid body"; } else if (result.post == 10) { post_result = "Invalid headers"; } else { post_colour = "orange"; post_result = "Remote too old for this test"; } } html += line('Local version', result.local_version, colours.local); html += line('Remote version', result.version, colours.remote); html += line('Status', status_message, colours.status); html += line('Compatibility', compatibility, compatibility_colour); html += line('POST test', post_result, post_colour); break; case 2: html += 'Server unreachable'; break; case 3: html += 'Unexpected error'; break; case 4: html += 'Authentication failed'; break; case 5: html += 'Password change required'; break; case 6: html += 'Terms not accepted'; break; case 7: html += 'Remote user not a sync user'; break; case 8: html += 'Remote user not a sync user, syncing sightings only'; break; } $("#connection_test_" + id).html(html); } }) } function getTextColour(hex) { hex = hex.slice(1); var r = parseInt(hex.substring(0,2), 16); var g = parseInt(hex.substring(2,4), 16); var b = parseInt(hex.substring(4,6), 16); var avg = ((2 * r) + b + (3 * g))/6; if (avg < 128) { return 'white'; } else { return 'black'; } } function gpgSelect(fingerprint) { $("#popover_form").fadeOut(); $("#gray_out").fadeOut(); $.ajax({ type: "get", url: baseurl + "/users/fetchGpgKey/" + fingerprint, beforeSend: function () { $(".loading").show(); }, success: function (data) { $("#UserGpgkey").val(data); showMessage('success', "Key found!"); }, error: function (data, textStatus, errorThrown) { showMessage('fail', textStatus + ": " + errorThrown); }, complete: function () { $(".loading").hide(); }, }); } function lookupPGPKey(emailFieldName) { var email = $('#' + emailFieldName).val(); simplePopup(baseurl + "/users/searchGpgKey/" + email); } function zeroMQServerAction(action) { $.ajax({ type: "get", url: baseurl + "/servers/" + action + "ZeroMQServer/", beforeSend: function (XMLHttpRequest) { $(".loading").show(); }, success: function (data) { $(".loading").hide(); if (action !== 'status') { window.location.reload(); } else { $("#confirmation_box").html(data); openPopup("#confirmation_box"); } }, error: function (data, textStatus, errorThrown) { showMessage('fail', textStatus + ": " + errorThrown); } }); } function convertServerFilterRules(rules) { validOptions.forEach(function (type) { container = "#"+ modelContext + type.ucfirst() + "Rules"; if ($(container).val() != '' && $(container).val() != '[]') { rules[type] = JSON.parse($(container).val()); } else { if (type === 'pull') { rules[type] = {"tags": {"OR": [], "NOT": []}, "orgs": {"OR": [], "NOT": []}, "url_params": ""} } else { rules[type] = {"tags": {"OR": [], "NOT": []}, "orgs": {"OR": [], "NOT": []}} } }; }); serverRuleUpdate(); return rules; } function serverRuleUpdate() { var statusOptions = ["OR", "NOT"]; validOptions.forEach(function(type) { validFields.forEach(function(field) { if (type === 'push') { var indexedList = {}; window[field].forEach(function(item) { indexedList[item.id] = item.name; }); } statusOptions.forEach(function(status) { if (rules[type][field][status].length > 0) { $('#' + type + '_' + field + '_' + status).show(); var t = ''; rules[type][field][status].forEach(function(item) { if (t.length > 0) t += ', '; if (type === 'pull') t += item; else t += indexedList[item]; }); $('#' + type + '_' + field + '_' + status + '_text').text(t); } else { $('#' + type + '_' + field + '_' + status).hide(); } }); }); if (type === 'pull') { if (rules[type]['url_params']) { $("#pull_url_params").show(); $("#pull_url_params_text").text(rules[type]['url_params']); } else { $("#pull_url_params").hide(); } } }); serverRuleGenerateJSON(); } function serverRuleFormActivate(type) { if (type != 'pull' && type != 'push') return false; $('.server_rule_popover').hide(); $('#gray_out').fadeIn(); $('#server_' + type + '_rule_popover').show(); } function serverRuleCancel() { $("#gray_out").fadeOut(); $(".server_rule_popover").fadeOut(); } function serverRuleGenerateJSON() { validOptions.forEach(function(type) { if ($('#Server' + type.ucfirst() + "Rules").length) { $('#Server' + type.ucfirst() + "Rules").val(JSON.stringify(rules[type])); } else { $('#Feed' + type.ucfirst() + "Rules").val(JSON.stringify(rules[type])); } }); } function serverRulePopulateTagPicklist() { var fields = ["tags", "orgs"]; var target = ""; fields.forEach(function(field) { target = ""; window[field].forEach(function(element) { if ($.inArray(element.id, rules["push"][field]["OR"]) != -1) target = "#" + field + "pushLeftValues"; else if ($.inArray(element.id, rules["push"][field]["NOT"]) != -1) target = "#" + field + "pushRightValues"; else target = "#" + field + "pushMiddleValues"; $(target).append($('