You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rspamd.js 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  1. /*
  2. The MIT License (MIT)
  3. Copyright (C) 2012-2013 Anton Simonov <untone@gmail.com>
  4. Copyright (C) 2014-2017 Vsevolod Stakhov <vsevolod@highsecure.ru>
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. */
  21. /* global jQuery:false, FooTable:false, Visibility:false */
  22. define(["jquery", "d3pie", "visibility", "nprogress", "stickytabs", "app/stats", "app/graph", "app/config",
  23. "app/symbols", "app/history", "app/upload"],
  24. // eslint-disable-next-line max-params
  25. function ($, D3pie, visibility, NProgress, stickyTabs, tab_stat, tab_graph, tab_config,
  26. tab_symbols, tab_history, tab_upload) {
  27. "use strict";
  28. var ui = {
  29. page_size: {
  30. scan: 25,
  31. errors: 25,
  32. history: 25
  33. },
  34. symbols: {
  35. scan: [],
  36. history: []
  37. }
  38. };
  39. var graphs = {};
  40. var tables = {};
  41. var neighbours = []; // list of clusters
  42. var checked_server = "All SERVERS";
  43. var timer_id = [];
  44. var selData = null; // Graph's dataset selector state
  45. var symbolDescriptions = {};
  46. NProgress.configure({
  47. minimum: 0.01,
  48. showSpinner: false,
  49. });
  50. function cleanCredentials() {
  51. sessionStorage.clear();
  52. $("#statWidgets").empty();
  53. $("#listMaps").empty();
  54. $("#modalBody").empty();
  55. }
  56. function stopTimers() {
  57. for (var key in timer_id) {
  58. if (!{}.hasOwnProperty.call(timer_id, key)) continue;
  59. Visibility.stop(timer_id[key]);
  60. }
  61. }
  62. function disconnect() {
  63. [graphs, tables].forEach(function (o) {
  64. Object.keys(o).forEach(function (key) {
  65. o[key].destroy();
  66. delete o[key];
  67. });
  68. });
  69. stopTimers();
  70. cleanCredentials();
  71. ui.connect();
  72. }
  73. function tabClick(id) {
  74. var tab_id = id;
  75. if ($(tab_id).attr("disabled")) return;
  76. $(tab_id).attr("disabled", true);
  77. stopTimers();
  78. if (tab_id === "#refresh") {
  79. tab_id = "#" + $(".navbar-nav .active > a").attr("id");
  80. }
  81. switch (tab_id) {
  82. case "#status_nav":
  83. tab_stat.statWidgets(ui, graphs, checked_server);
  84. timer_id.status = Visibility.every(10000, function () {
  85. tab_stat.statWidgets(ui, graphs, checked_server);
  86. });
  87. break;
  88. case "#throughput_nav":
  89. tab_graph.draw(ui, graphs, tables, neighbours, checked_server, selData);
  90. var autoRefresh = {
  91. hourly: 60000,
  92. daily: 300000
  93. };
  94. timer_id.throughput = Visibility.every(autoRefresh[selData] || 3600000, function () {
  95. tab_graph.draw(ui, graphs, tables, neighbours, checked_server, selData);
  96. });
  97. break;
  98. case "#configuration_nav":
  99. tab_config.getActions(ui, checked_server);
  100. tab_config.getMaps(ui, checked_server);
  101. break;
  102. case "#symbols_nav":
  103. tab_symbols.getSymbols(ui, tables, checked_server);
  104. break;
  105. case "#history_nav":
  106. tab_history.getHistory(ui, tables);
  107. tab_history.getErrors(ui, tables);
  108. break;
  109. case "#disconnect":
  110. disconnect();
  111. break;
  112. default:
  113. }
  114. setTimeout(function () {
  115. $(tab_id).removeAttr("disabled");
  116. $("#refresh").removeAttr("disabled");
  117. }, 1000);
  118. }
  119. function drawTooltips() {
  120. // Update symbol description tooltips
  121. $.each(symbolDescriptions, function (key, description) {
  122. $("abbr[data-sym-key=" + key + "]").tooltip({
  123. placement: "bottom",
  124. html: true,
  125. title: description
  126. });
  127. });
  128. }
  129. function getPassword() {
  130. return sessionStorage.getItem("Password");
  131. }
  132. // Get selectors' current state
  133. function getSelector(id) {
  134. var e = document.getElementById(id);
  135. return e.options[e.selectedIndex].value;
  136. }
  137. function get_compare_function(table) {
  138. var compare_functions = {
  139. magnitude: function (e1, e2) {
  140. return Math.abs(e2.score) - Math.abs(e1.score);
  141. },
  142. name: function (e1, e2) {
  143. return e1.name.localeCompare(e2.name);
  144. },
  145. score: function (e1, e2) {
  146. return e2.score - e1.score;
  147. }
  148. };
  149. return compare_functions[getSelector("selSymOrder_" + table)];
  150. }
  151. function saveCredentials(password) {
  152. sessionStorage.setItem("Password", password);
  153. }
  154. function set_page_size(table, page_size, callback) {
  155. var n = parseInt(page_size, 10); // HTML Input elements return string representing a number
  156. if (n !== ui.page_size[table] && n > 0) {
  157. ui.page_size[table] = n;
  158. if (callback) {
  159. return callback(n);
  160. }
  161. }
  162. return null;
  163. }
  164. function sort_symbols(o, compare_function) {
  165. return Object.keys(o)
  166. .map(function (key) {
  167. return o[key];
  168. })
  169. .sort(compare_function)
  170. .map(function (e) { return e.str; })
  171. .join("<br>\n");
  172. }
  173. function unix_time_format(tm) {
  174. var date = new Date(tm ? tm * 1000 : 0);
  175. return date.toLocaleString();
  176. }
  177. function displayUI() {
  178. ui.query("auth", {
  179. success: function (neighbours_status) {
  180. $("#selSrv").empty();
  181. $("#selSrv").append($('<option value="All SERVERS">All SERVERS</option>'));
  182. neighbours_status.forEach(function (e) {
  183. $("#selSrv").append($('<option value="' + e.name + '">' + e.name + "</option>"));
  184. if (checked_server === e.name) {
  185. $('#selSrv [value="' + e.name + '"]').prop("selected", true);
  186. } else if (!e.status) {
  187. $('#selSrv [value="' + e.name + '"]').prop("disabled", true);
  188. }
  189. });
  190. },
  191. errorMessage: "Cannot get server status",
  192. server: "All SERVERS"
  193. });
  194. // In many browsers local storage can only store string.
  195. // So when we store the boolean true or false, it actually stores the strings "true" or "false".
  196. ui.read_only = sessionStorage.getItem("read_only") === "true";
  197. if (ui.read_only) {
  198. $(".learn").hide();
  199. $("#resetHistory").attr("disabled", true);
  200. $("#errors-history").hide();
  201. } else {
  202. $(".learn").show();
  203. $("#resetHistory").removeAttr("disabled", true);
  204. $("#errors-history").show();
  205. }
  206. var buttons = $("#navBar .pull-right");
  207. $("#mainUI").show();
  208. $(buttons).show();
  209. $(".nav-tabs-sticky").stickyTabs({initialTab:"#status_nav"});
  210. }
  211. function alertMessage(alertClass, alertText) {
  212. var a = $("<div class=\"alert " + alertClass + " alert-dismissible fade in show\">" +
  213. "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" title=\"Dismiss\">&times;</button>" +
  214. "<strong>" + alertText + "</strong>");
  215. $(".notification-area").append(a);
  216. setTimeout(function () {
  217. $(a).fadeTo(500, 0).slideUp(500, function () {
  218. $(this).alert("close");
  219. });
  220. }, 5000);
  221. }
  222. function queryServer(neighbours_status, ind, req_url, o) {
  223. neighbours_status[ind].checked = false;
  224. neighbours_status[ind].data = {};
  225. neighbours_status[ind].status = false;
  226. var req_params = {
  227. jsonp: false,
  228. data: o.data,
  229. headers: $.extend({Password:getPassword()}, o.headers),
  230. url: neighbours_status[ind].url + req_url,
  231. xhr: function () {
  232. var xhr = $.ajaxSettings.xhr();
  233. // Download progress
  234. if (req_url !== "neighbours") {
  235. xhr.addEventListener("progress", function (e) {
  236. if (e.lengthComputable) {
  237. neighbours_status[ind].percentComplete = e.loaded / e.total;
  238. var percentComplete = neighbours_status.reduce(function (prev, curr) {
  239. return curr.percentComplete ? curr.percentComplete + prev : prev;
  240. }, 0);
  241. NProgress.set(percentComplete / neighbours_status.length);
  242. }
  243. }, false);
  244. }
  245. return xhr;
  246. },
  247. success: function (json) {
  248. neighbours_status[ind].checked = true;
  249. neighbours_status[ind].status = true;
  250. neighbours_status[ind].data = json;
  251. },
  252. error: function (jqXHR, textStatus, errorThrown) {
  253. neighbours_status[ind].checked = true;
  254. function errorMessage() {
  255. alertMessage("alert-error", neighbours_status[ind].name + " > " +
  256. (o.errorMessage ? o.errorMessage : "Request failed") +
  257. (errorThrown ? ": " + errorThrown : ""));
  258. }
  259. if (o.error) {
  260. o.error(neighbours_status[ind],
  261. jqXHR, textStatus, errorThrown);
  262. } else if (o.errorOnceId) {
  263. var alert_status = o.errorOnceId + neighbours_status[ind].name;
  264. if (!(alert_status in sessionStorage)) {
  265. sessionStorage.setItem(alert_status, true);
  266. errorMessage();
  267. }
  268. } else {
  269. errorMessage();
  270. }
  271. },
  272. complete: function (jqXHR) {
  273. if (neighbours_status.every(function (elt) { return elt.checked; })) {
  274. if (neighbours_status.some(function (elt) { return elt.status; })) {
  275. if (o.success) {
  276. o.success(neighbours_status, jqXHR);
  277. } else {
  278. alertMessage("alert-success", "Request completed");
  279. }
  280. } else {
  281. alertMessage("alert-error", "Request failed");
  282. }
  283. NProgress.done();
  284. }
  285. },
  286. statusCode: o.statusCode
  287. };
  288. if (o.method) {
  289. req_params.method = o.method;
  290. }
  291. if (o.params) {
  292. $.each(o.params, function (k, v) {
  293. req_params[k] = v;
  294. });
  295. }
  296. $.ajax(req_params);
  297. }
  298. // Public functions
  299. ui.alertMessage = alertMessage;
  300. ui.setup = function () {
  301. $("#selData").change(function () {
  302. selData = this.value;
  303. tabClick("#throughput_nav");
  304. });
  305. $.ajaxSetup({
  306. timeout: 20000,
  307. jsonp: false
  308. });
  309. $(document).ajaxStart(function () {
  310. $("#navBar").addClass("loading");
  311. });
  312. $(document).ajaxComplete(function () {
  313. setTimeout(function () {
  314. $("#navBar").removeClass("loading");
  315. }, 1000);
  316. });
  317. $("a[data-toggle=\"tab\"]").on("shown.bs.tab", function (e) {
  318. var tab_id = "#" + $(e.target).attr("id");
  319. tabClick(tab_id);
  320. });
  321. $("a[data-toggle=\"button\"]").on("click", function (e) {
  322. var tab_id = "#" + $(e.target).attr("id");
  323. tabClick(tab_id);
  324. });
  325. $("#selSrv").change(function () {
  326. checked_server = this.value;
  327. $("#selSrv [value=\"" + checked_server + "\"]").prop("checked", true);
  328. tabClick("#" + $("#navBar ul li.active > a").attr("id"));
  329. });
  330. // Radio buttons
  331. $(document).on("click", "input:radio[name=\"clusterName\"]", function () {
  332. if (!this.disabled) {
  333. checked_server = this.value;
  334. tabClick("#status_nav");
  335. }
  336. });
  337. tab_config.setup(ui);
  338. tab_history.setup(ui, tables);
  339. tab_symbols.setup(ui, tables);
  340. tab_upload.setup(ui, tables);
  341. selData = tab_graph.setup(ui);
  342. };
  343. ui.connect = function () {
  344. // Query "/stat" to check if user is already logged in or client ip matches "secure_ip"
  345. $.ajax({
  346. type: "GET",
  347. url: "stat",
  348. async: false,
  349. success: function () {
  350. displayUI();
  351. },
  352. error: function () {
  353. var dialog = $("#connectDialog");
  354. var backdrop = $("#backDrop");
  355. $("#mainUI").hide();
  356. $(dialog).show();
  357. $(backdrop).show();
  358. $("#connectPassword").focus();
  359. $("#connectForm").off("submit");
  360. $("#connectForm").on("submit", function (e) {
  361. e.preventDefault();
  362. var password = $("#connectPassword").val();
  363. if (!(/^[\u0020-\u007e]*$/).test(password)) {
  364. alertMessage("alert-modal alert-error", "Invalid characters in the password");
  365. $("#connectPassword").focus();
  366. return;
  367. }
  368. ui.query("auth", {
  369. headers: {
  370. Password: password
  371. },
  372. success: function (json) {
  373. var data = json[0].data;
  374. $("#connectPassword").val("");
  375. if (data.auth === "ok") {
  376. sessionStorage.setItem("read_only", data.read_only);
  377. saveCredentials(password);
  378. $(dialog).hide();
  379. $(backdrop).hide();
  380. displayUI();
  381. }
  382. },
  383. error: function (jqXHR) {
  384. ui.alertMessage("alert-modal alert-error", jqXHR.statusText);
  385. $("#connectPassword").val("");
  386. $("#connectPassword").focus();
  387. },
  388. params: {
  389. global: false,
  390. },
  391. server: "local"
  392. });
  393. });
  394. }
  395. });
  396. };
  397. ui.drawPie = function (object, id, data, conf) {
  398. var obj = object;
  399. if (obj) {
  400. obj.updateProp("data.content",
  401. data.filter(function (elt) {
  402. return elt.value > 0;
  403. })
  404. );
  405. } else {
  406. obj = new D3pie(id,
  407. $.extend({}, {
  408. header: {
  409. title: {
  410. text: "Rspamd filter stats",
  411. fontSize: 24,
  412. font: "open sans"
  413. },
  414. subtitle: {
  415. color: "#999999",
  416. fontSize: 12,
  417. font: "open sans"
  418. },
  419. titleSubtitlePadding: 9
  420. },
  421. footer: {
  422. color: "#999999",
  423. fontSize: 10,
  424. font: "open sans",
  425. location: "bottom-left"
  426. },
  427. size: {
  428. canvasWidth: 600,
  429. canvasHeight: 400,
  430. pieInnerRadius: "20%",
  431. pieOuterRadius: "85%"
  432. },
  433. data: {
  434. // "sortOrder": "value-desc",
  435. content: data.filter(function (elt) {
  436. return elt.value > 0;
  437. })
  438. },
  439. labels: {
  440. outer: {
  441. hideWhenLessThanPercentage: 1,
  442. pieDistance: 30
  443. },
  444. inner: {
  445. hideWhenLessThanPercentage: 4
  446. },
  447. mainLabel: {
  448. fontSize: 14
  449. },
  450. percentage: {
  451. color: "#eeeeee",
  452. fontSize: 14,
  453. decimalPlaces: 0
  454. },
  455. lines: {
  456. enabled: true
  457. },
  458. truncation: {
  459. enabled: true
  460. }
  461. },
  462. tooltips: {
  463. enabled: true,
  464. type: "placeholder",
  465. string: "{label}: {value} ({percentage}%)"
  466. },
  467. effects: {
  468. pullOutSegmentOnClick: {
  469. effect: "back",
  470. speed: 400,
  471. size: 8
  472. },
  473. load: {
  474. effect: "none"
  475. }
  476. },
  477. misc: {
  478. gradient: {
  479. enabled: true,
  480. percentage: 100
  481. }
  482. }
  483. }, conf));
  484. }
  485. return obj;
  486. };
  487. ui.getPassword = getPassword;
  488. ui.getSelector = getSelector;
  489. /**
  490. * @param {string} url - A string containing the URL to which the request is sent
  491. * @param {Object} [options] - A set of key/value pairs that configure the Ajax request. All settings are optional.
  492. *
  493. * @param {Object|string|Array} [options.data] - Data to be sent to the server.
  494. * @param {Function} [options.error] - A function to be called if the request fails.
  495. * @param {string} [options.errorMessage] - Text to display in the alert message if the request fails.
  496. * @param {string} [options.errorOnceId] - A prefix of the alert ID to be added to the session storage. If the
  497. * parameter is set, the error for each server will be displayed only once per session.
  498. * @param {Object} [options.headers] - An object of additional header key/value pairs to send along with requests
  499. * using the XMLHttpRequest transport.
  500. * @param {string} [options.method] - The HTTP method to use for the request.
  501. * @param {Object} [options.params] - An object of additional jQuery.ajax() settings key/value pairs.
  502. * @param {string} [options.server] - A server to which send the request.
  503. * @param {Function} [options.success] - A function to be called if the request succeeds.
  504. *
  505. * @returns {undefined}
  506. */
  507. ui.query = function (url, options) {
  508. // Force options to be an object
  509. var o = options || {};
  510. Object.keys(o).forEach(function (option) {
  511. if (["data", "error", "errorMessage", "errorOnceId", "headers", "method", "params", "server", "statusCode",
  512. "success"]
  513. .indexOf(option) < 0) {
  514. throw new Error("Unknown option: " + option);
  515. }
  516. });
  517. var neighbours_status = [{
  518. name: "local",
  519. host: "local",
  520. url: "",
  521. }];
  522. o.server = o.server || checked_server;
  523. if (o.server === "All SERVERS") {
  524. queryServer(neighbours_status, 0, "neighbours", {
  525. success: function (json) {
  526. var data = json[0].data;
  527. if (jQuery.isEmptyObject(data)) {
  528. neighbours = {
  529. local: {
  530. host: window.location.host,
  531. url: window.location.origin + window.location.pathname
  532. }
  533. };
  534. } else {
  535. neighbours = data;
  536. }
  537. neighbours_status = [];
  538. $.each(neighbours, function (ind) {
  539. neighbours_status.push({
  540. name: ind,
  541. host: neighbours[ind].host,
  542. url: neighbours[ind].url,
  543. });
  544. });
  545. $.each(neighbours_status, function (ind) {
  546. queryServer(neighbours_status, ind, url, o);
  547. });
  548. },
  549. errorMessage: "Cannot receive neighbours data"
  550. });
  551. } else {
  552. if (o.server !== "local") {
  553. neighbours_status = [{
  554. name: o.server,
  555. host: neighbours[o.server].host,
  556. url: neighbours[o.server].url,
  557. }];
  558. }
  559. queryServer(neighbours_status, 0, url, o);
  560. }
  561. };
  562. // Scan and History shared functions
  563. ui.drawTooltips = drawTooltips;
  564. ui.unix_time_format = unix_time_format;
  565. ui.set_page_size = set_page_size;
  566. ui.bindHistoryTableEventHandlers = function (table, symbolsCol) {
  567. function change_symbols_order(order) {
  568. $(".btn-sym-" + table + "-" + order).addClass("active").siblings().removeClass("active");
  569. var compare_function = get_compare_function(table);
  570. $.each(tables[table].rows.all, function (i, row) {
  571. var cell_val = sort_symbols(ui.symbols[table][i], compare_function);
  572. row.cells[symbolsCol].val(cell_val, false, true);
  573. });
  574. drawTooltips();
  575. }
  576. $("#selSymOrder_" + table).unbind().change(function () {
  577. var order = this.value;
  578. change_symbols_order(order);
  579. });
  580. $("#" + table + "_page_size").change(function () {
  581. set_page_size(table, this.value, function (n) { tables[table].pageSize(n); });
  582. });
  583. $(document).on("click", ".btn-sym-order-" + table + " button", function () {
  584. var order = this.value;
  585. $("#selSymOrder_" + table).val(order);
  586. change_symbols_order(order);
  587. });
  588. };
  589. ui.destroyTable = function (table) {
  590. if (tables[table]) {
  591. tables[table].destroy();
  592. delete tables[table];
  593. }
  594. };
  595. ui.initHistoryTable = function (rspamd, data, items, table, columns, expandFirst) {
  596. /* eslint-disable consistent-this, no-underscore-dangle, one-var-declaration-per-line */
  597. FooTable.actionFilter = FooTable.Filtering.extend({
  598. construct: function (instance) {
  599. this._super(instance);
  600. this.actions = ["reject", "add header", "greylist",
  601. "no action", "soft reject", "rewrite subject"];
  602. this.def = "Any action";
  603. this.$action = null;
  604. },
  605. $create: function () {
  606. this._super();
  607. var self = this, $form_grp = $("<div/>", {
  608. class: "form-group"
  609. }).append($("<label/>", {
  610. class: "sr-only",
  611. text: "Action"
  612. })).prependTo(self.$form);
  613. self.$action = $("<select/>", {
  614. class: "form-control"
  615. }).on("change", {
  616. self: self
  617. }, self._onStatusDropdownChanged).append(
  618. $("<option/>", {
  619. text: self.def
  620. })).appendTo($form_grp);
  621. $.each(self.actions, function (i, action) {
  622. self.$action.append($("<option/>").text(action));
  623. });
  624. },
  625. _onStatusDropdownChanged: function (e) {
  626. var self = e.data.self, selected = $(this).val();
  627. if (selected !== self.def) {
  628. if (selected === "reject") {
  629. self.addFilter("action", "reject -soft", ["action"]);
  630. } else {
  631. self.addFilter("action", selected, ["action"]);
  632. }
  633. } else {
  634. self.removeFilter("action");
  635. }
  636. self.filter();
  637. },
  638. draw: function () {
  639. this._super();
  640. var action = this.find("action");
  641. if (action instanceof FooTable.Filter) {
  642. if (action.query.val() === "reject -soft") {
  643. this.$action.val("reject");
  644. } else {
  645. this.$action.val(action.query.val());
  646. }
  647. } else {
  648. this.$action.val(this.def);
  649. }
  650. }
  651. });
  652. /* eslint-enable consistent-this, no-underscore-dangle, one-var-declaration-per-line */
  653. tables[table] = FooTable.init("#historyTable_" + table, {
  654. columns: columns,
  655. rows: items,
  656. expandFirst: expandFirst,
  657. paging: {
  658. enabled: true,
  659. limit: 5,
  660. size: ui.page_size[table]
  661. },
  662. filtering: {
  663. enabled: true,
  664. position: "left",
  665. connectors: false
  666. },
  667. sorting: {
  668. enabled: true
  669. },
  670. components: {
  671. filtering: FooTable.actionFilter
  672. },
  673. on: {
  674. "ready.ft.table": drawTooltips,
  675. "after.ft.sorting": drawTooltips,
  676. "after.ft.paging": drawTooltips,
  677. "after.ft.filtering": drawTooltips,
  678. "expand.ft.row": function (e, ft, row) {
  679. setTimeout(function () {
  680. var detail_row = row.$el.next();
  681. var order = getSelector("selSymOrder_" + table);
  682. detail_row.find(".btn-sym-" + table + "-" + order)
  683. .addClass("active").siblings().removeClass("active");
  684. }, 5);
  685. }
  686. }
  687. });
  688. };
  689. ui.preprocess_item = function (rspamd, item) {
  690. function escapeHTML(string) {
  691. var htmlEscaper = /[&<>"'/`=]/g;
  692. var htmlEscapes = {
  693. "&": "&amp;",
  694. "<": "&lt;",
  695. ">": "&gt;",
  696. "\"": "&quot;",
  697. "'": "&#39;",
  698. "/": "&#x2F;",
  699. "`": "&#x60;",
  700. "=": "&#x3D;"
  701. };
  702. return String(string).replace(htmlEscaper, function (match) {
  703. return htmlEscapes[match];
  704. });
  705. }
  706. function escape_HTML_array(arr) {
  707. arr.forEach(function (d, i) { arr[i] = escapeHTML(d); });
  708. }
  709. for (var prop in item) {
  710. if (!{}.hasOwnProperty.call(item, prop)) continue;
  711. switch (prop) {
  712. case "rcpt_mime":
  713. case "rcpt_smtp":
  714. escape_HTML_array(item[prop]);
  715. break;
  716. case "symbols":
  717. Object.keys(item.symbols).forEach(function (key) {
  718. var sym = item.symbols[key];
  719. if (!sym.name) {
  720. sym.name = key;
  721. }
  722. sym.name = escapeHTML(sym.name);
  723. if (sym.description) {
  724. sym.description = escapeHTML(sym.description);
  725. }
  726. if (sym.options) {
  727. escape_HTML_array(sym.options);
  728. }
  729. });
  730. break;
  731. default:
  732. if (typeof item[prop] === "string") {
  733. item[prop] = escapeHTML(item[prop]);
  734. }
  735. }
  736. }
  737. if (item.action === "clean" || item.action === "no action") {
  738. item.action = "<div style='font-size:11px' class='label label-success'>" + item.action + "</div>";
  739. } else if (item.action === "rewrite subject" || item.action === "add header" || item.action === "probable spam") {
  740. item.action = "<div style='font-size:11px' class='label label-warning'>" + item.action + "</div>";
  741. } else if (item.action === "spam" || item.action === "reject") {
  742. item.action = "<div style='font-size:11px' class='label label-danger'>" + item.action + "</div>";
  743. } else {
  744. item.action = "<div style='font-size:11px' class='label label-info'>" + item.action + "</div>";
  745. }
  746. var score_content = (item.score < item.required_score)
  747. ? "<span class='text-success'>" + item.score.toFixed(2) + " / " + item.required_score + "</span>"
  748. : "<span class='text-danger'>" + item.score.toFixed(2) + " / " + item.required_score + "</span>";
  749. item.score = {
  750. options: {
  751. sortValue: item.score
  752. },
  753. value: score_content
  754. };
  755. };
  756. ui.process_history_v2 = function (rspamd, data, table) {
  757. // Display no more than rcpt_lim recipients
  758. var rcpt_lim = 3;
  759. var items = [];
  760. var unsorted_symbols = [];
  761. var compare_function = get_compare_function(table);
  762. $("#selSymOrder_" + table + ", label[for='selSymOrder_" + table + "']").show();
  763. $.each(data.rows,
  764. function (i, item) {
  765. function more(p) {
  766. var l = item[p].length;
  767. return (l > rcpt_lim) ? " … (" + l + ")" : "";
  768. }
  769. function format_rcpt(smtp, mime) {
  770. var full = "";
  771. var shrt = "";
  772. if (smtp) {
  773. full = "[" + item.rcpt_smtp.join(", ") + "] ";
  774. shrt = "[" + item.rcpt_smtp.slice(0, rcpt_lim).join(",&#8203;") + more("rcpt_smtp") + "]";
  775. if (mime) {
  776. full += " ";
  777. shrt += " ";
  778. }
  779. }
  780. if (mime) {
  781. full += item.rcpt_mime.join(", ");
  782. shrt += item.rcpt_mime.slice(0, rcpt_lim).join(",&#8203;") + more("rcpt_mime");
  783. }
  784. return {full:full, shrt:shrt};
  785. }
  786. function get_symbol_class(name, score) {
  787. if (name.match(/^GREYLIST$/)) {
  788. return "symbol-special";
  789. }
  790. if (score < 0) {
  791. return "symbol-negative";
  792. } else if (score > 0) {
  793. return "symbol-positive";
  794. }
  795. return null;
  796. }
  797. rspamd.preprocess_item(rspamd, item);
  798. Object.keys(item.symbols).forEach(function (key) {
  799. var sym = item.symbols[key];
  800. sym.str = '<span class="symbol-default ' + get_symbol_class(sym.name, sym.score) + '"><strong>';
  801. if (sym.description) {
  802. sym.str += '<abbr data-sym-key="' + key + '">' +
  803. sym.name + "</abbr></strong> (" + sym.score + ")</span>";
  804. // Store description for tooltip
  805. symbolDescriptions[key] = sym.description;
  806. } else {
  807. sym.str += sym.name + "</strong> (" + sym.score + ")</span>";
  808. }
  809. if (sym.options) {
  810. sym.str += " [" + sym.options.join(",") + "]";
  811. }
  812. });
  813. unsorted_symbols.push(item.symbols);
  814. item.symbols = sort_symbols(item.symbols, compare_function);
  815. if (table === "scan") {
  816. item.unix_time = (new Date()).getTime() / 1000;
  817. }
  818. item.time = {
  819. value: unix_time_format(item.unix_time),
  820. options: {
  821. sortValue: item.unix_time
  822. }
  823. };
  824. item.time_real = item.time_real.toFixed(3);
  825. item.id = item["message-id"];
  826. if (table === "history") {
  827. var rcpt = {};
  828. if (!item.rcpt_mime.length) {
  829. rcpt = format_rcpt(true, false);
  830. } else if ($(item.rcpt_mime).not(item.rcpt_smtp).length !== 0 || $(item.rcpt_smtp).not(item.rcpt_mime).length !== 0) {
  831. rcpt = format_rcpt(true, true);
  832. } else {
  833. rcpt = format_rcpt(false, true);
  834. }
  835. item.rcpt_mime_short = rcpt.shrt;
  836. item.rcpt_mime = rcpt.full;
  837. if (item.sender_mime !== item.sender_smtp) {
  838. item.sender_mime = "[" + item.sender_smtp + "] " + item.sender_mime;
  839. }
  840. }
  841. items.push(item);
  842. });
  843. return {items:items, symbols:unsorted_symbols};
  844. };
  845. ui.waitForRowsDisplayed = function (table, rows_total, callback, iteration) {
  846. var i = (typeof iteration === "undefined") ? 10 : iteration;
  847. var num_rows = $("#historyTable_" + table + " > tbody > tr:not(.footable-detail-row)").length;
  848. if (num_rows === ui.page_size[table] ||
  849. num_rows === rows_total) {
  850. return callback();
  851. } else if (--i) {
  852. setTimeout(function () {
  853. ui.waitForRowsDisplayed(table, rows_total, callback, i);
  854. }, 500);
  855. }
  856. return null;
  857. };
  858. return ui;
  859. });