shared.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. function get_object_fields(obj) {
  2. var field_array = [];
  3. obj = flatten_json(obj._source)
  4. for (field in obj) {
  5. field_array.push(field);
  6. }
  7. return field_array.sort();
  8. }
  9. function get_all_fields(json) {
  10. var field_array = [];
  11. var obj_fields;
  12. for (hit in json.hits.hits) {
  13. obj_fields = get_object_fields(json.hits.hits[hit]);
  14. for (index in obj_fields) {
  15. if (_.indexOf(field_array,obj_fields[index]) < 0) {
  16. field_array.push(obj_fields[index]);
  17. }
  18. }
  19. }
  20. return field_array.sort();
  21. }
  22. function has_field(obj,field) {
  23. var obj_fields = get_object_fields(obj);
  24. if (_.inArray(obj_fields,field) < 0) {
  25. return false;
  26. } else {
  27. return true;
  28. }
  29. }
  30. // Retuns a sorted array with duplicates removed
  31. function array_unique(arr) {
  32. var sorted_arr = arr.sort();
  33. var results = [];
  34. for (var i = 0; i <= arr.length - 1; i++) {
  35. if (sorted_arr[i + 1] != sorted_arr[i]) {
  36. results.push(sorted_arr[i]);
  37. }
  38. }
  39. return results
  40. }
  41. function get_objids_with_field(json,field) {
  42. var objid_array = [];
  43. for (hit in json.hits.hits) {
  44. if(has_field(json.hits.hits[hit],field)) {
  45. objid_array.push(hit);
  46. }
  47. }
  48. return objid_array;
  49. }
  50. function get_objids_with_field_value(json,field,value) {
  51. var objid_array = [];
  52. for (hit in json.hits.hits) {
  53. var hit_obj = json.hits.hits[hit];
  54. if(has_field(hit_obj,field)) {
  55. var field_val = get_field_value(hit_obj,field,'raw')
  56. if(_.isArray(field_val)) {
  57. if(_.inArray(field_val,field) >= 0) {
  58. objid_array.push(hit);
  59. }
  60. } else {
  61. if(field_val == value) {
  62. objid_array.push(hit);
  63. }
  64. }
  65. } else {
  66. if ( value == '')
  67. objid_array.push(hit);
  68. }
  69. }
  70. return objid_array;
  71. }
  72. function get_related_fields(json,field) {
  73. var field_array = []
  74. for (hit in json.hits.hits) {
  75. var obj_fields = get_object_fields(json.hits.hits[hit])
  76. if (_.inArray(obj_fields,field) >= 0) {
  77. field_array.push.apply(field_array,obj_fields);
  78. }
  79. }
  80. var counts = count_values_in_array(field_array);
  81. return counts;
  82. }
  83. function recurse_field_dots(object,field) {
  84. var value = null;
  85. if (typeof object[field] != 'undefined')
  86. value = object[field];
  87. else if (nested = field.match(/(.*?)\.(.*)/))
  88. if(typeof object[nested[1]] != 'undefined')
  89. value = (typeof object[nested[1]][nested[2]] != 'undefined') ?
  90. object[nested[1]][nested[2]] : recurse_field_dots(
  91. object[nested[1]],nested[2]);
  92. return value;
  93. }
  94. // Probably useless now
  95. function get_field_value(object,field,opt) {
  96. var value = recurse_field_dots(object['_source'],field);
  97. if(value === null)
  98. return ''
  99. if(_.isArray(value))
  100. if (opt == 'raw') {
  101. return value;
  102. }
  103. else {
  104. var complex = false;
  105. _.each(value, function(el, index) {
  106. if (typeof(el) == 'object') {
  107. complex = true;
  108. }
  109. })
  110. if (complex) {
  111. return JSON.stringify(value, null, 4);
  112. }
  113. return value.toString();
  114. }
  115. if(typeof value === 'object' && value != null)
  116. // Leaving this out for now
  117. //return opt == 'raw' ? value : JSON.stringify(value,null,4)
  118. return JSON.stringify(value,null,4)
  119. return (value != null) ? value.toString() : '';
  120. }
  121. // Returns a big flat array of all values for a field
  122. function get_all_values_for_field(docs,field) {
  123. var field_array = [];
  124. _.each(docs, function(doc,k) {
  125. var value = doc[field] || ""
  126. if(typeof value === 'object' && value != null) {
  127. field_array.push.apply(field_array,value);
  128. } else {
  129. field_array.push(value);
  130. }
  131. })
  132. return field_array;
  133. }
  134. function top_field_values(docs,field,count) {
  135. var counts = _.countBy(get_all_values_for_field(docs,field),function(field){return field;});
  136. return _.pairs(counts).sort(function(a, b) {return a[1] - b[1]}).reverse().slice(0,count)
  137. }
  138. function add_to_query(original,field,value) {
  139. if(value !== '')
  140. var query = field + ":" + "\"" + addslashes(value.toString()) + "\"";
  141. else
  142. var query = "_missing_:" + field;
  143. var glue = original != "" ? " AND " : "";
  144. return original + glue + query;
  145. }
  146. /**
  147. * Calculate a graph interval
  148. *
  149. * from:: Date object containing the start time
  150. * to:: Date object containing the finish time
  151. * size:: Calculate to approximately this many bars
  152. * user_interval:: User specified histogram interval
  153. *
  154. */
  155. function calculate_interval(from,to,size,user_interval) {
  156. if(_.isObject(from))
  157. from = from.getTime();
  158. if(_.isObject(to))
  159. to = to.getTime();
  160. return user_interval == 0 ? round_interval((to - from)/size) : user_interval;
  161. }
  162. function get_bar_count(from,to,interval) {
  163. return (to - from)/interval;
  164. }
  165. function round_interval (interval) {
  166. switch (true) {
  167. case (interval <= 500): return 100;
  168. case (interval <= 5000): return 1000;
  169. case (interval <= 7500): return 5000;
  170. case (interval <= 15000): return 10000;
  171. case (interval <= 45000): return 30000;
  172. case (interval <= 180000): return 60000;
  173. case (interval <= 450000): return 300000;
  174. case (interval <= 1200000): return 600000;
  175. case (interval <= 2700000): return 1800000;
  176. case (interval <= 7200000): return 3600000;
  177. case (interval <= 21600000): return 10800000;
  178. default: return 43200000;
  179. }
  180. }
  181. function secondsToHms(seconds){
  182. var numyears = Math.floor(seconds / 31536000);
  183. if(numyears){
  184. return numyears + 'y';
  185. }
  186. var numdays = Math.floor((seconds % 31536000) / 86400);
  187. if(numdays){
  188. return numdays + 'd';
  189. }
  190. var numhours = Math.floor(((seconds % 31536000) % 86400) / 3600);
  191. if(numhours){
  192. return numhours + 'h';
  193. }
  194. var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);
  195. if(numminutes){
  196. return numminutes + 'm';
  197. }
  198. var numseconds = (((seconds % 31536000) % 86400) % 3600) % 60;
  199. if(numseconds){
  200. return numseconds + 's';
  201. }
  202. return 'less then a second'; //'just now' //or other string you like;
  203. }
  204. function to_percent(number,outof) {
  205. return Math.round((number/outof)*10000)/100 + "%";
  206. }
  207. function addslashes(str) {
  208. str = str.replace(/\\/g, '\\\\');
  209. str = str.replace(/\'/g, '\\\'');
  210. str = str.replace(/\"/g, '\\"');
  211. str = str.replace(/\0/g, '\\0');
  212. return str;
  213. }
  214. // Create an ISO8601 compliant timestamp for ES
  215. //function ISODateString(unixtime) {
  216. //var d = new Date(parseInt(unixtime));
  217. function ISODateString(d) {
  218. if(is_int(d)) {
  219. d = new Date(parseInt(d));
  220. }
  221. function pad(n) {
  222. return n < 10 ? '0' + n : n
  223. }
  224. return d.getFullYear() + '-' +
  225. pad(d.getMonth() + 1) + '-' +
  226. pad(d.getDate()) + 'T' +
  227. pad(d.getHours()) + ':' +
  228. pad(d.getMinutes()) + ':' +
  229. pad(d.getSeconds());
  230. }
  231. function pickDateString(d) {
  232. return dateFormat(d,'yyyy-mm-dd HH:MM:ss')
  233. }
  234. function prettyDateString(d) {
  235. d = new Date(parseInt(d));
  236. d = utc_date_obj(d);
  237. return dateFormat(d,window.time_format);
  238. }
  239. function utc_date_obj(d) {
  240. return new Date(
  241. d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(),
  242. d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(),
  243. d.getUTCMilliseconds());
  244. }
  245. function local_date_obj(d) {
  246. return new Date(Date.UTC(
  247. d.getFullYear(), d.getMonth(), d.getDate(),
  248. d.getHours(), d.getMinutes(), d.getSeconds()));
  249. }
  250. function is_int(value) {
  251. if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) {
  252. return true;
  253. } else {
  254. return false;
  255. }
  256. }
  257. function interval_to_seconds(string) {
  258. var matches = string.match(/(\d+)([Mwdhms])/);
  259. switch (matches[2]) {
  260. case 'M': return matches[1]*2592000;;
  261. case 'w': return matches[1]*604800;;
  262. case 'd': return matches[1]*86400;;
  263. case 'h': return matches[1]*3600;;
  264. case 'm': return matches[1]*60;;
  265. case 's': return matches[1];
  266. }
  267. }
  268. function time_ago(string) {
  269. return new Date(new Date().getTime() - (interval_to_seconds(string)*1000))
  270. }
  271. function flatten_json(object,root,array) {
  272. if (typeof array === 'undefined')
  273. var array = {};
  274. if (typeof root === 'undefined')
  275. var root = '';
  276. for(var index in object) {
  277. var obj = object[index]
  278. var rootname = root.length == 0 ? index : root + '.' + index;
  279. if(typeof obj == 'object' ) {
  280. if(_.isArray(obj))
  281. array[rootname] = typeof obj === 'undefined' ? null : obj.join(',');
  282. else
  283. flatten_json(obj,rootname,array)
  284. } else {
  285. array[rootname] = typeof obj === 'undefined' ? null : obj;
  286. }
  287. }
  288. return sortObj(array);
  289. }
  290. function xmlEnt(value) {
  291. if(_.isString(value)) {
  292. var stg1 = value.replace(/</g, '&lt;')
  293. .replace(/>/g, '&gt;')
  294. .replace(/\r\n/g, '<br/>')
  295. .replace(/\r/g, '<br/>')
  296. .replace(/\n/g, '<br/>')
  297. .replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;')
  298. .replace(/ /g, '&nbsp;&nbsp;')
  299. .replace(/&lt;del&gt;/g, '<del>')
  300. .replace(/&lt;\/del&gt;/g, '</del>');
  301. return stg1
  302. } else {
  303. return value
  304. }
  305. }
  306. function sortObj(arr) {
  307. // Setup Arrays
  308. var sortedKeys = new Array();
  309. var sortedObj = {};
  310. // Separate keys and sort them
  311. for (var i in arr) {
  312. sortedKeys.push(i);
  313. }
  314. sortedKeys.sort();
  315. // Reconstruct sorted obj based on keys
  316. for (var i in sortedKeys) {
  317. sortedObj[sortedKeys[i]] = arr[sortedKeys[i]];
  318. }
  319. return sortedObj;
  320. }
  321. // WTF. Has to be a better way to do this. Hi Tyler.
  322. function int_to_tz(offset) {
  323. var hour = offset / 1000 / 3600
  324. var str = ""
  325. if (hour == 0) {
  326. str = "+0000"
  327. }
  328. if (hour < 0) {
  329. if (hour > -10)
  330. str = "-0" + (hour * -100)
  331. else
  332. str = "-" + (hour * -100)
  333. }
  334. if (hour > 0) {
  335. if (hour < 10)
  336. str = "+0" + (hour * 100)
  337. else
  338. str = "+" + (hour * 100)
  339. }
  340. str = str.substring(0,3) + ":" + str.substring(3);
  341. return str
  342. }
  343. // Sets #hash, thus refreshing results
  344. function setHash(json) {
  345. window.location.hash = encodeURIComponent(Base64.encode(JSON.stringify(json)));
  346. }
  347. // Add commas to numbers
  348. function addCommas(nStr) {
  349. nStr += '';
  350. var x = nStr.split('.');
  351. var x1 = x[0];
  352. var x2 = x.length > 1 ? '.' + x[1] : '';
  353. var rgx = /(\d+)(\d{3})/;
  354. while (rgx.test(x1)) {
  355. x1 = x1.replace(rgx, '$1' + ',' + '$2');
  356. }
  357. return x1 + x2;
  358. }
  359. // Split up log spaceless strings
  360. // Str = string to split
  361. // num = number of letters between <wbr> tags
  362. function wbr(str, num) {
  363. str = htmlEntities(str);
  364. return str.replace(
  365. RegExp("(@?\\w{" + num + "}|[:;,])([\\w\"'])([\\w@]*)", "g"),
  366. function (all, text, char, trailer) {
  367. if (/@KIBANA_\w+_(START|END)@/.test(all)) {
  368. return text + char + trailer;
  369. } else {
  370. return text + "<del>&#8203;</del>" + char + trailer;
  371. }
  372. }
  373. );
  374. }
  375. function htmlEntities(str) {
  376. return String(str).replace(
  377. /&/g, '&amp;').replace(
  378. /</g, '&lt;').replace(
  379. />/g, '&gt;').replace(
  380. /"/g, '&quot;');
  381. }
  382. _.mixin({
  383. move: function (array, fromIndex, toIndex) {
  384. array.splice(toIndex, 0, array.splice(fromIndex, 1)[0] );
  385. return array;
  386. }
  387. });
  388. _.mixin({
  389. remove: function (array, index) {
  390. array.splice(index, 1);
  391. return array;
  392. }
  393. });