extends layout

include mixins

block content
  if suser.userId != user.userId
    h1.red Administrator changing data for user '#{suser.userId}'
  h2 Settings
  form#changeSettings
    input(type='hidden', id='token', name='token', value='#{token}')
    h3 General
    label(for='timezone') Timezone format:
    select#timezone.setting(name="timezone")
      option(value="local") local time
      option(value="gmt") gmt time
    br
    h3 Sessions Tab
    label(for='detailFormat') Session Detail Format:
    select#detailFormat.setting(name="detailFormat")
      option(value="last") last used
      option(value="natural") natural
      option(value="ascii") ascii
      option(value="utf8") utf8
      option(value="hex") hex
    br
    label(for='showTimestamps') Show Timestamps:
    select#showTimestamps.setting(name="showTimestamps")
      option(value="last") last used
      option(value="true") on
      option(value="false") off
    br
    label(for='sortColumn') Sessions Sort Column:
    select#sortColumn.setting(name="sortColumn")
      option(value="start") Start Time
      option(value="stop") Stop Time
      option(value="srcip") Src IP
      option(value="srcport") Src Port
      option(value="dstip") Dst IP
      option(value="dstport") Dst Port
      option(value="packets") Packets
      option(value="bytes") Bytes
      option(value="node") Node
    select#sortDirection.setting(name="sortDirection")
      option(value="asc") Ascending
      option(value="desc") Descending
    h3 SPI Graph Tab
    label(for='spiGraph') Default Graph:
    +fieldsSelect("spiGraph", "setting", false)
    h3 Connections Tab
    label(for='connSrcField') Default Src Field:
    +fieldsSelect("connSrcField", "setting", true)
    br
    label(for='connDstField') Default Dst Field:
    +fieldsSelect("connDstField", "setting", true, [{dbField: "ip.dst:port", exp: "ip.dst:port"}])
  p
  hr
  h2 Views
  p Saved views provide an easier method to specify common base queries and can be activated in the navigation header.
  if (suser.views)
    h3 Current Views
    table#views(cellpadding="0",cellspacing="0",border="0",class="display",style="table { clear: both }")
      thead
        tr
          th.viewName(style="width:150px") Name
          th.viewExpression Expression
          th.viewAction(style="width:50px") Action
      tbody
        - var keys = Object.keys(suser.views).sort()
        each key in keys
          tr
            td(contentEditable) #{key}
            td(contentEditable) #{suser.views[key].expression}
            td
              a.deleteViewAction(href="#") delete

  p
  h3 New View
  form#createViewForm
    input(type='hidden', id='token', name='token', value='#{token}')
    label(for='viewName') View Name:
    input(id='viewName', name='viewName', size='30', maxlength='20')
    br
    label(for='viewExpression') Expression:
    input(id='viewExpression', name='viewExpression', size='100')
    p
    center
      button#createView Create View
  hr
  h2 Change Password
  form#changePasswordForm
    input(type='hidden', id='token', name='token', value='#{token}')
    - if (currentPassword)
      label(for='currentPassword') Current Password:
      input(type='password', id='currentPassword', name='currentPassword', size='30')
      br
    label(for='newPassword') New Password:
    input(type='password', id='newPassword', name='newPassword', size='30')
    br
    label(for='newPassword2') New Password:
    input(type='password', id='newPassword2', name='newPassword2', size='30')
    p
    center
      button#change Change Password
  p
  hr
  h2 Cron Queries
  p Allow queries to be run periodically that can perform actions on sessions that match the queries.  The query runs against sessions delayed by 90 second to make sure all updates have been completed for that session.
  if (suser.queries)
    h3 Current Queries
    table#queries(cellpadding="0",cellspacing="0",border="0",class="display",style="table { clear: both }")
      thead
        tr
          th.queryProcessed(style="width:50px") Processed
          th.queryEnabled(style="width:50px") Enabled
          th.queryName(style="width:150px") Name
          th.queryExpression Expression
          th.queryActions(style="width:150px") Actions
          th.queryTags Tags
          th.queryAction(style="width:50px") Action
      tbody
        - var keys = Object.keys(suser.queries).sort()
        each key in keys
          tr(key="#{key}")
            td #{suser.queries[key].count || 0}
            td
              input.cronQueryEnabled(type='checkbox', CHECKED=suser.queries[key].enabled)
            td(contentEditable) #{suser.queries[key].name}
            td(contentEditable) #{suser.queries[key].query}
            td
              select
                each action in actions
                  option(value=action.value,SELECTED=suser.queries[key].action==action.value) #{action.name}
            td(contentEditable) #{suser.queries[key].tags}
            td
              a.deleteCronQueryAction(href="#") delete
  p
  h3 New Cron Query
  form#createCQForm
    input(type='hidden', name='token', value='#{token}')
    input(type='hidden', name='key', value='_create_')
    input(type='hidden', name='enabled', value='true')
    label(for='cqName') Name:
    input(id='cqName', name='name', size='30', maxlength='20')
    br
    label(for='cqExpression') Expression:
    input(id='cqExpression', name='query', size='100')
    br
    label(for='cqAction') Action:
    select(id='cqAction',name='action')
      each action in actions
        option(value=action.value) #{action.name}
    br
    label(for='cqTags') Comma seperated tags:
    input(id='cqTags', name='tags', size='100')
    br
    label(for='cqSince') Start Processing Since:
    select(id='cqSince',name='since')
      option(value=0,selected) Now
      option(value=1) 1 hr ago
      option(value=6) 6 hrs ago
      option(value=24) 24 hrs ago
      option(value=48) 48 hrs ago
      option(value=72) 3 days ago
      option(value=168) Week ago
      option(value=720) Month ago
      option(value=4380) 6 Months ago
      option(value=-1) All
    br
    p
    center
      button#createCQ Create Cron Query

  script(type='text/javascript').
    var settings  = !{JSON.stringify(suser.settings)};


    $(document).ready(function() {
      // Selects
      var defaults = {
        spiGraph: "no",
        connSrcField: "a1",
        connDstField: "ip.dst:port"
      };

      ["timezone", "detailFormat", "showTimestamps", "sortColumn", "sortDirection", "spiGraph", "connSrcField", "connDstField"].forEach(function(field) {
        if (settings[field]) {
          $("#" + field + " option[value='" + settings[field] + "']").attr('selected', 'selected');
        } else if (defaults[field]) {
          $("#" + field + " option[value='" + defaults[field] + "']").attr('selected', 'selected');
        }
      });

      $('#views').dataTable({
        oLanguage: {
          "sLengthMenu": "_MENU_"
        },
        sDom: '<"fg-toolbar ui-widget-header ui-helper-clearfix"lipfr>t',
        aoColumns: [
        null,
        null,
        {
          bSearchable: false,
          bSortable: false
        }
        ]
      });

      $('#queries').dataTable({
        "oLanguage": {
          "sLengthMenu": "_MENU_"
        },
        "sDom": '<"fg-toolbar ui-widget-header ui-helper-clearfix"lipfr>t',
        aoColumns: [
          null,
          {
            sSortDataType: "dom-checkbox"
          },
          null,
          null,
          {
            sSortDataType: "dom-select"
          },
          null,
          {
            bSearchable: false,
            bSortable: false
          }
        ]
      });
    });


    $('#changePasswordForm').submit(function() {
      if ($("#newPassword").val() != $("#newPassword2").val()) {
        alert("New passwords don't match");
        return false;
      }

      $.ajax( {
        "dataType": 'json',
        "type": "POST",
        "url": "#{basePath}changePassword",
        "data": $("#changePasswordForm").serialize(),
        "success": function(data) {
          if (!data.success) {
            alert(data.text);
          } else {
            alert("Password changed.");
          }
        }
      });
      return false;
    });

    $(document).on('change', '.setting', function (e) {
      $.ajax( {
        "dataType": 'json',
        "type": "POST",
        "url": "#{basePath}changeSettings",
        "data": $("#changeSettings").serialize(),
        "success": function(data) {
          if (!data.success) {
            alert(data.text);
          }
        }
      });
    });

    $('#createViewForm').submit(function() {
      $.ajax( {
        "dataType": 'json',
        "type": "POST",
        "url": "#{basePath}updateView",
        "data": $("#createViewForm").serialize(),
        "success": function(data) {
          if (!data.success) {
            alert(data.text);
          } else {
            location.reload();
          }
        }
      });
      return false;
    });

    $('#createCQForm').submit(function() {
      $.ajax( {
        "dataType": 'json',
        "type": "POST",
        "url": "#{basePath}updateCronQuery",
        "data": $("#createCQForm").serialize(),
        "success": function(data) {
          if (!data.success) {
            alert(data.text);
          } else {
            location.reload();
          }
        }
      });
      return false;
    });

    $(document).on('click', '.deleteViewAction', function (e) {
      $.ajax( {
        "dataType": 'json',
        "type": "POST",
        "url": "#{basePath}deleteView",
        "data": [{name: "view", value: $(this).closest("tr").find("td:first").text()},
                 {name: "token", value: "#{token}"}],
        "success": function(data) {
          if (!data.success) {
            alert(data.text);
          } else {
            location.reload();
          }
        }
      });
      return false;
    });

    $(document).on('focusout', '#views td[contentEditable]', function () {
      var row = $(this).closest("tr");
      $.ajax( {
        "dataType": 'json',
        "type": "POST",
        "url": "#{basePath}updateView",
        "data": [{name: "viewName", value: row.find("td:first").text()},
                 {name: "viewExpression", value: row.find("td:eq(1)").text()},
                 {name: "token", value: "#{token}"}],
        "success": function(data) {
          if (!data.success) {
            alert(data.text);
          }
        }
      });
    });

    $(document).on('click', '.deleteCronQueryAction', function (e) {
      $.ajax( {
        "dataType": 'json',
        "type": "POST",
        "url": "#{basePath}deleteCronQuery",
        "data": [{name: "key", value: $(this).closest("tr").attr("key")},
                 {name: "token", value: "#{token}"}],
        "success": function(data) {
          if (!data.success) {
            alert(data.text);
          } else {
            location.reload();
          }
        }
      });
      return false;
    });

    function saveCQRow(row) {
      $.ajax( {
        "dataType": 'json',
        "type": "POST",
        "url": "#{basePath}updateCronQuery",
        "data": [{name: "key", value: row.attr("key")},
                 {name: "enabled", value: row.find("td:eq(1) input").is(':checked')?"true":"false"},
                 {name: "name", value: row.find("td:eq(2)").text()},
                 {name: "query", value: row.find("td:eq(3)").text()},
                 {name: "action", value: row.find("td:eq(4) select").val()},
                 {name: "tags", value: row.find("td:eq(5)").text()},
                 {name: "token", value: "#{token}"}],
        "success": function(data) {
          if (!data.success) {
            alert(data.text);
          }
        }
      });
    }

    $(document).on('focusout', '#queries td[contentEditable]', function () {
      var row = $(this).closest("tr");
      saveCQRow(row);
    });

    $(document).on('change', '#queries input, #queries select', function (e) {
      saveCQRow($(e.target).closest("tr"));
    });

    $(document).on('keypress', 'td[contentEditable]', function (e) {
      if ((e.keyCode ? e.keyCode : e.which) === 13) {
        e.target.blur();
        return false;
      }
    });

    // From http://datatables.net/examples/plug-ins/dom_sort.html
    /* Create an array with the values of all the select options in a column */
    $.fn.dataTableExt.afnSortData['dom-select'] = function  ( oSettings, iColumn )
    {
      var aData = [];
      $( 'td:eq('+iColumn+') select', oSettings.oApi._fnGetTrNodes(oSettings) ).each( function () {
        aData.push( $(this).val() );
      } );
      return aData;
    }

    /* Create an array with the values of all the checkboxes in a column */
    $.fn.dataTableExt.afnSortData['dom-checkbox'] = function  ( oSettings, iColumn )
    {
      var aData = [];
      $( 'td:eq('+iColumn+') input', oSettings.oApi._fnGetTrNodes(oSettings) ).each( function () {
        aData.push( this.checked==true ? "1" : "0" );
      } );
      return aData;
    }
