shared.js 11 KB

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