1"use strict"; 2/* DokuWiki BotMon Plugin Script file */ 3/* 12.09.2025 - 0.3.0 - beta */ 4/* Author: Sascha Leib <ad@hominem.info> */ 5 6// enumeration of user types: 7const BM_USERTYPE = Object.freeze({ 8 'UNKNOWN': 'unknown', 9 'KNOWN_USER': 'user', 10 'PROBABLY_HUMAN': 'human', 11 'LIKELY_BOT': 'likely_bot', 12 'KNOWN_BOT': 'known_bot' 13}); 14 15// enumeration of log types: 16const BM_LOGTYPE = Object.freeze({ 17 'SERVER': 'srv', 18 'CLIENT': 'log', 19 'TICKER': 'tck' 20}); 21 22// enumeration of IP versions: 23const BM_IPVERSION = Object.freeze({ 24 'IPv4': 4, 25 'IPv6': 6 26}); 27 28/* BotMon root object */ 29const BotMon = { 30 31 init: function() { 32 //console.info('BotMon.init()'); 33 34 // find the plugin basedir: 35 this._baseDir = document.currentScript.src.substring(0, document.currentScript.src.indexOf('/exe/')) 36 + '/plugins/botmon/'; 37 38 // read the page language from the DOM: 39 this._lang = document.getRootNode().documentElement.lang || this._lang; 40 41 // get the time offset: 42 this._timeDiff = BotMon.t._getTimeOffset(); 43 44 // get yesterday's date: 45 let d = new Date(); 46 d.setDate(d.getDate() - 1); 47 this._datestr = d.toISOString().slice(0, 10); 48 49 // init the sub-objects: 50 BotMon.t._callInit(this); 51 }, 52 53 _baseDir: null, 54 _lang: 'en', 55 _datestr: '', 56 _timeDiff: '', 57 58 /* internal tools */ 59 t: { 60 /* helper function to call inits of sub-objects */ 61 _callInit: function(obj) { 62 //console.info('BotMon.t._callInit(obj=',obj,')'); 63 64 /* call init / _init on each sub-object: */ 65 Object.keys(obj).forEach( (key,i) => { 66 const sub = obj[key]; 67 let init = null; 68 if (typeof sub === 'object' && sub.init) { 69 init = sub.init; 70 } 71 72 // bind to object 73 if (typeof init == 'function') { 74 const init2 = init.bind(sub); 75 init2(obj); 76 } 77 }); 78 }, 79 80 /* helper function to calculate the time difference to UTC: */ 81 _getTimeOffset: function() { 82 const now = new Date(); 83 let offset = now.getTimezoneOffset(); // in minutes 84 const sign = Math.sign(offset); // +1 or -1 85 offset = Math.abs(offset); // always positive 86 87 let hours = 0; 88 while (offset >= 60) { 89 hours += 1; 90 offset -= 60; 91 } 92 return ( hours > 0 ? sign * hours + ' h' : '') + (offset > 0 ? ` ${offset} min` : ''); 93 }, 94 95 /* helper function to create a new element with all attributes and text content */ 96 _makeElement: function(name, atlist = undefined, text = undefined) { 97 var r = null; 98 try { 99 r = document.createElement(name); 100 if (atlist) { 101 for (let attr in atlist) { 102 r.setAttribute(attr, atlist[attr]); 103 } 104 } 105 if (text) { 106 r.textContent = text.toString(); 107 } 108 } catch(e) { 109 console.error(e); 110 } 111 return r; 112 }, 113 114 /* helper to convert an ip address string to a normalised format: */ 115 _ip2Num: function(ip) { 116 if (!ip) { 117 return 'null'; 118 } else if (ip.indexOf(':') > 0) { /* IP6 */ 119 return (ip.split(':').map(d => ('0000'+d).slice(-4) ).join(':')); 120 } else { /* IP4 */ 121 return ip.split('.').map(d => ('000'+d).slice(-3) ).join('.'); 122 } 123 }, 124 125 /* helper function to format a Date object to show only the time. */ 126 /* returns String */ 127 _formatTime: function(date) { 128 129 if (date) { 130 return date.getHours() + ':' + ('0'+date.getMinutes()).slice(-2) + ':' + ('0'+date.getSeconds()).slice(-2); 131 } else { 132 return null; 133 } 134 135 }, 136 137 /* helper function to show a time difference in seconds or minutes */ 138 /* returns String */ 139 _formatTimeDiff: function(dateA, dateB) { 140 141 // if the second date is ealier, swap them: 142 if (dateA > dateB) dateB = [dateA, dateA = dateB][0]; 143 144 // get the difference in milliseconds: 145 let ms = dateB - dateA; 146 147 if (ms > 50) { /* ignore small time spans */ 148 const h = Math.floor((ms / (1000 * 60 * 60)) % 24); 149 const m = Math.floor((ms / (1000 * 60)) % 60); 150 const s = Math.floor((ms / 1000) % 60); 151 152 return ( h>0 ? h + 'h ': '') + ( m>0 ? m + 'm ': '') + ( s>0 ? s + 's': ''); 153 } 154 155 return null; 156 157 }, 158 159 // calcualte a reduced ration between two numbers 160 // adapted from https://stackoverflow.com/questions/3946373/math-in-js-how-do-i-get-a-ratio-from-a-percentage 161 _getRatio: function(a, b, tolerance) { 162 163 var bg = b; 164 var sm = a; 165 if (a > b) { 166 var bg = a; 167 var sm = b; 168 } 169 170 for (var i = 1; i < 1000000; i++) { 171 var d = sm / i; 172 var res = bg / d; 173 var howClose = Math.abs(res - res.toFixed(0)); 174 if (howClose < tolerance) { 175 if (a > b) { 176 return res.toFixed(0) + ':' + i; 177 } else { 178 return i + ':' + res.toFixed(0); 179 } 180 } 181 } 182 } 183 } 184}; 185 186/* everything specific to the "Latest" tab is self-contained in the "live" object: */ 187BotMon.live = { 188 init: function() { 189 //console.info('BotMon.live.init()'); 190 191 // set the title: 192 const tDiff = '(<abbr title="Coordinated Universal Time">UTC</abbr>' + (BotMon._timeDiff != '' ? `, ${BotMon._timeDiff}` : '' ) + ')'; 193 BotMon.live.gui.status.setTitle(`Data for <time datetime="${BotMon._datestr}">${BotMon._datestr}</time> ${tDiff}`); 194 195 // init sub-objects: 196 BotMon.t._callInit(this); 197 }, 198 199 data: { 200 init: function() { 201 //console.info('BotMon.live.data.init()'); 202 203 // call sub-inits: 204 BotMon.t._callInit(this); 205 }, 206 207 // this will be called when the known json files are done loading: 208 _dispatch: function(file) { 209 //console.info('BotMon.live.data._dispatch(,',file,')'); 210 211 // shortcut to make code more readable: 212 const data = BotMon.live.data; 213 214 // set the flags: 215 switch(file) { 216 case 'rules': 217 data._dispatchRulesLoaded = true; 218 break; 219 case 'ipranges': 220 data._dispatchIPRangesLoaded = true; 221 break; 222 case 'bots': 223 data._dispatchBotsLoaded = true; 224 break; 225 case 'clients': 226 data._dispatchClientsLoaded = true; 227 break; 228 case 'platforms': 229 data._dispatchPlatformsLoaded = true; 230 break; 231 default: 232 // ignore 233 } 234 235 // are all the flags set? 236 if (data._dispatchBotsLoaded && data._dispatchClientsLoaded && data._dispatchPlatformsLoaded && data._dispatchRulesLoaded && data._dispatchIPRangesLoaded) { 237 // chain the log files loading: 238 BotMon.live.data.loadLogFile(BM_LOGTYPE.SERVER, BotMon.live.data._onServerLogLoaded); 239 } 240 }, 241 // flags to track which data files have been loaded: 242 _dispatchBotsLoaded: false, 243 _dispatchClientsLoaded: false, 244 _dispatchPlatformsLoaded: false, 245 _dispatchIPRangesLoaded: false, 246 _dispatchRulesLoaded: false, 247 248 // event callback, after the server log has been loaded: 249 _onServerLogLoaded: function() { 250 //console.info('BotMon.live.data._onServerLogLoaded()'); 251 252 // chain the client log file to load: 253 BotMon.live.data.loadLogFile(BM_LOGTYPE.CLIENT, BotMon.live.data._onClientLogLoaded); 254 }, 255 256 // event callback, after the client log has been loaded: 257 _onClientLogLoaded: function() { 258 //console.info('BotMon.live.data._onClientLogLoaded()'); 259 260 // chain the ticks file to load: 261 BotMon.live.data.loadLogFile(BM_LOGTYPE.TICKER, BotMon.live.data._onTicksLogLoaded); 262 263 }, 264 265 // event callback, after the tiker log has been loaded: 266 _onTicksLogLoaded: function() { 267 //console.info('BotMon.live.data._onTicksLogLoaded()'); 268 269 // analyse the data: 270 BotMon.live.data.analytics.analyseAll(); 271 272 // sort the data: 273 // #TODO 274 275 // display the data: 276 BotMon.live.gui.overview.make(); 277 278 //console.log(BotMon.live.data.model._visitors); 279 280 }, 281 282 // the data model: 283 model: { 284 // visitors storage: 285 _visitors: [], 286 287 // find an already existing visitor record: 288 findVisitor: function(visitor, type) { 289 //console.info('BotMon.live.data.model.findVisitor()', type); 290 //console.log(visitor); 291 292 // shortcut to make code more readable: 293 const model = BotMon.live.data.model; 294 295 const timeout = 60 * 60 * 1000; // session timeout: One hour 296 297 if (visitor._type == BM_USERTYPE.KNOWN_BOT) { // known bots match by their bot ID: 298 299 for (let i=0; i<model._visitors.length; i++) { 300 const v = model._visitors[i]; 301 302 // bots match when their ID matches: 303 if (v._bot && v._bot.id == visitor._bot.id) { 304 return v; 305 } 306 } 307 } else { // other types match by their DW/PHPIDs: 308 309 // loop over all visitors already registered and check for ID matches: 310 for (let i=0; i<model._visitors.length; i++) { 311 const v = model._visitors[i]; 312 313 if ( v.id == visitor.id) { // match the DW/PHP IDs 314 return v; 315 } 316 } 317 318 // if not found, try to match IP address and user agent: 319 for (let i=0; i<model._visitors.length; i++) { 320 const v = model._visitors[i]; 321 if ( v.ip == visitor.ip && v.agent == visitor.agent) { 322 return v; 323 } 324 } 325 } 326 327 return null; // nothing found 328 }, 329 330 /* if there is already this visit registered, return the page view item */ 331 _getPageView: function(visit, view) { 332 333 // shortcut to make code more readable: 334 const model = BotMon.live.data.model; 335 336 for (let i=0; i<visit._pageViews.length; i++) { 337 const pv = visit._pageViews[i]; 338 if (pv.pg == view.pg) { 339 return pv; 340 } 341 } 342 return null; // not found 343 }, 344 345 // register a new visitor (or update if already exists) 346 registerVisit: function(nv, type) { 347 //console.info('registerVisit', nv, type); 348 349 // shortcut to make code more readable: 350 const model = BotMon.live.data.model; 351 352 // is it a known bot? 353 const bot = BotMon.live.data.bots.match(nv.agent); 354 355 // enrich new visitor with relevant data: 356 if (!nv._bot) nv._bot = bot ?? null; // bot info 357 nv._type = ( bot ? BM_USERTYPE.KNOWN_BOT : ( nv.usr && nv.usr !== '' ? BM_USERTYPE.KNOWN_USER : BM_USERTYPE.UNKNOWN ) ); // user type 358 if (bot && bot.geo) { 359 if (!nv.geo || nv.geo == '' || nv.geo == 'ZZ') nv.geo = bot.geo; 360 } else if (!nv.geo ||nv.geo == '') { 361 nv.geo = 'ZZ'; 362 } 363 364 // update first and last seen: 365 if (!nv._firstSeen) nv._firstSeen = nv.ts; // first-seen 366 nv._lastSeen = nv.ts; // last-seen 367 368 // country name: 369 try { 370 nv._country = ( nv.geo == 'local' ? "localhost" : "Unknown" ); 371 if (nv.geo && nv.geo !== '' && nv.geo !== 'ZZ' && nv.geo !== 'local') { 372 const countryName = new Intl.DisplayNames(['en', BotMon._lang], {type: 'region'}); 373 nv._country = countryName.of(nv.geo.substring(0,2)) ?? nv.geo; 374 } 375 } catch (err) { 376 console.error(err); 377 nv._country = 'Error'; 378 } 379 380 // check if it already exists: 381 let visitor = model.findVisitor(nv, type); 382 if (!visitor) { 383 visitor = nv; 384 visitor._seenBy = [type]; 385 visitor._pageViews = []; // array of page views 386 visitor._hasReferrer = false; // has at least one referrer 387 visitor._jsClient = false; // visitor has been seen logged by client js as well 388 visitor._client = BotMon.live.data.clients.match(nv.agent) ?? null; // client info 389 visitor._platform = BotMon.live.data.platforms.match(nv.agent); // platform info 390 model._visitors.push(visitor); 391 } else { // update existing 392 if (visitor._firstSeen > nv.ts) { 393 visitor._firstSeen = nv.ts; 394 } 395 } 396 397 // find browser 398 399 // is this visit already registered? 400 let prereg = model._getPageView(visitor, nv); 401 if (!prereg) { 402 // add new page view: 403 prereg = model._makePageView(nv, type); 404 visitor._pageViews.push(prereg); 405 } else { 406 // update last seen date 407 prereg._lastSeen = nv.ts; 408 // increase view count: 409 prereg._viewCount += 1; 410 prereg._tickCount += 1; 411 } 412 413 // update referrer state: 414 visitor._hasReferrer = visitor._hasReferrer || 415 (prereg.ref !== undefined && prereg.ref !== ''); 416 417 // update time stamp for last-seen: 418 if (visitor._lastSeen < nv.ts) { 419 visitor._lastSeen = nv.ts; 420 } 421 422 // if needed: 423 return visitor; 424 }, 425 426 // updating visit data from the client-side log: 427 updateVisit: function(dat) { 428 //console.info('updateVisit', dat); 429 430 // shortcut to make code more readable: 431 const model = BotMon.live.data.model; 432 433 const type = BM_LOGTYPE.CLIENT; 434 435 let visitor = BotMon.live.data.model.findVisitor(dat, type); 436 if (!visitor) { 437 visitor = model.registerVisit(dat, type); 438 } 439 if (visitor) { 440 441 if (visitor._lastSeen < dat.ts) { 442 visitor._lastSeen = dat.ts; 443 } 444 if (!visitor._seenBy.includes(type)) { 445 visitor._seenBy.push(type); 446 } 447 visitor._jsClient = true; // seen by client js 448 } 449 450 // find the page view: 451 let prereg = BotMon.live.data.model._getPageView(visitor, dat); 452 if (prereg) { 453 // update the page view: 454 prereg._lastSeen = dat.ts; 455 if (!prereg._seenBy.includes(type)) prereg._seenBy.push(type); 456 prereg._jsClient = true; // seen by client js 457 } else { 458 // add the page view to the visitor: 459 prereg = model._makePageView(dat, type); 460 visitor._pageViews.push(prereg); 461 } 462 prereg._tickCount += 1; 463 }, 464 465 // updating visit data from the ticker log: 466 updateTicks: function(dat) { 467 //console.info('updateTicks', dat); 468 469 // shortcut to make code more readable: 470 const model = BotMon.live.data.model; 471 472 const type = BM_LOGTYPE.TICKER; 473 474 // find the visit info: 475 let visitor = model.findVisitor(dat, type); 476 if (!visitor) { 477 console.info(`No visitor with ID “${dat.id}” found, registering as a new one.`); 478 visitor = model.registerVisit(dat, type); 479 } 480 if (visitor) { 481 // update visitor: 482 if (visitor._lastSeen < dat.ts) visitor._lastSeen = dat.ts; 483 if (!visitor._seenBy.includes(type)) visitor._seenBy.push(type); 484 485 // get the page view info: 486 let pv = model._getPageView(visitor, dat); 487 if (!pv) { 488 console.info(`No page view for visit ID “${dat.id}”, page “${dat.pg}”, registering a new one.`); 489 pv = model._makePageView(dat, type); 490 visitor._pageViews.push(pv); 491 } 492 493 // update the page view info: 494 if (!pv._seenBy.includes(type)) pv._seenBy.push(type); 495 if (pv._lastSeen.getTime() < dat.ts.getTime()) pv._lastSeen = dat.ts; 496 pv._tickCount += 1; 497 498 } 499 }, 500 501 // helper function to create a new "page view" item: 502 _makePageView: function(data, type) { 503 // console.info('_makePageView', data); 504 505 // try to parse the referrer: 506 let rUrl = null; 507 try { 508 rUrl = ( data.ref && data.ref !== '' ? new URL(data.ref) : null ); 509 } catch (e) { 510 console.warn(`Invalid referer: “${data.ref}”.`); 511 console.info(data); 512 } 513 514 return { 515 _by: type, 516 ip: data.ip, 517 pg: data.pg, 518 lang: data.lang || '??', 519 _ref: rUrl, 520 _firstSeen: data.ts, 521 _lastSeen: data.ts, 522 _seenBy: [type], 523 _jsClient: ( type !== BM_LOGTYPE.SERVER), 524 _viewCount: 1, 525 _tickCount: 0 526 }; 527 } 528 }, 529 530 // functions to analyse the data: 531 analytics: { 532 533 /** 534 * Initializes the analytics data storage object: 535 */ 536 init: function() { 537 //console.info('BotMon.live.data.analytics.init()'); 538 }, 539 540 // data storage: 541 data: { 542 totalVisits: 0, 543 totalPageViews: 0, 544 humanPageViews: 0, 545 bots: { 546 known: 0, 547 suspected: 0, 548 human: 0, 549 users: 0 550 } 551 }, 552 553 // sort the visits by type: 554 groups: { 555 knownBots: [], 556 suspectedBots: [], 557 humans: [], 558 users: [] 559 }, 560 561 // all analytics 562 analyseAll: function() { 563 //console.info('BotMon.live.data.analytics.analyseAll()'); 564 565 // shortcut to make code more readable: 566 const model = BotMon.live.data.model; 567 const me = BotMon.live.data.analytics; 568 569 BotMon.live.gui.status.showBusy("Analysing data …"); 570 571 // loop over all visitors: 572 model._visitors.forEach( (v) => { 573 574 // count visits and page views: 575 this.data.totalVisits += 1; 576 this.data.totalPageViews += v._pageViews.length; 577 578 // check for typical bot aspects: 579 let botScore = 0; 580 581 if (v._type == BM_USERTYPE.KNOWN_BOT) { // known bots 582 583 this.data.bots.known += v._pageViews.length; 584 this.groups.knownBots.push(v); 585 586 } else if (v._type == BM_USERTYPE.KNOWN_USER) { // known users */ 587 588 this.data.bots.users += v._pageViews.length; 589 this.groups.users.push(v); 590 591 } else { 592 593 // get evaluation: 594 const e = BotMon.live.data.rules.evaluate(v); 595 v._eval = e.rules; 596 v._botVal = e.val; 597 598 if (e.isBot) { // likely bots 599 v._type = BM_USERTYPE.LIKELY_BOT; 600 this.data.bots.suspected += v._pageViews.length; 601 this.groups.suspectedBots.push(v); 602 } else { // probably humans 603 v._type = BM_USERTYPE.PROBABLY_HUMAN; 604 this.data.bots.human += v._pageViews.length; 605 this.groups.humans.push(v); 606 } 607 } 608 609 // perform actions depending on the visitor type: 610 if (v._type == BM_USERTYPE.KNOWN_BOT || v._type == BM_USERTYPE.LIKELY_BOT) { /* bots only */ 611 612 // add bot views to IP range information: 613 /*v._pageViews.forEach( pv => { 614 me.addToIPRanges(pv.ip); 615 });*/ 616 617 618 } else { /* humans only */ 619 620 // add browser and platform statistics: 621 me.addBrowserPlatform(v); 622 623 // add 624 v._pageViews.forEach( pv => { 625 me.addToRefererList(pv._ref); 626 me.addToPagesList(pv.pg); 627 }); 628 } 629 630 // add to the country lists: 631 me.addToCountries(v.geo, v._country, v._type); 632 633 }); 634 635 BotMon.live.gui.status.hideBusy('Done.'); 636 }, 637 638 // get a list of known bots: 639 getTopBots: function(max) { 640 //console.info('BotMon.live.data.analytics.getTopBots('+max+')'); 641 642 //console.log(BotMon.live.data.analytics.groups.knownBots); 643 644 let botsList = BotMon.live.data.analytics.groups.knownBots.toSorted( (a, b) => { 645 return b._pageViews.length - a._pageViews.length; 646 }); 647 648 const other = { 649 'id': 'other', 650 'name': "Others", 651 'count': 0 652 }; 653 654 const rList = []; 655 const max2 = ( botsList.length > max ? max-1 : botsList.length ); 656 let total = 0; // adding up the items 657 for (let i=0; i<botsList.length; i++) { 658 const it = botsList[i]; 659 if (it && it._bot) { 660 if (i < max2) { 661 rList.push({ 662 id: it._bot.id, 663 name: (it._bot.n ? it._bot.n : it._bot.id), 664 count: it._pageViews.length 665 }); 666 } else { 667 other.count += it._pageViews.length; 668 }; 669 total += it._pageViews.length; 670 } 671 }; 672 673 // add the "other" item, if needed: 674 if (botsList.length > max2) { 675 rList.push(other); 676 }; 677 678 rList.forEach( it => { 679 it.pct = (it.count * 100 / total); 680 }); 681 682 return rList; 683 }, 684 685 // most visited pages list: 686 _pagesList: [], 687 688 /** 689 * Add a page view to the list of most visited pages. 690 * @param {string} pageId - The page ID to add to the list. 691 * @example 692 * BotMon.live.data.analytics.addToPagesList('1234567890'); 693 */ 694 addToPagesList: function(pageId) { 695 //console.log('BotMon.live.data.analytics.addToPagesList', pageId); 696 697 const me = BotMon.live.data.analytics; 698 699 // already exists? 700 let pgObj = null; 701 for (let i = 0; i < me._pagesList.length; i++) { 702 if (me._pagesList[i].id == pageId) { 703 pgObj = me._pagesList[i]; 704 break; 705 } 706 } 707 708 // if not exists, create it: 709 if (!pgObj) { 710 pgObj = { 711 id: pageId, 712 count: 1 713 }; 714 me._pagesList.push(pgObj); 715 } else { 716 pgObj.count += 1; 717 } 718 }, 719 720 getTopPages: function(max) { 721 //console.info('BotMon.live.data.analytics.getTopPages('+max+')'); 722 const me = BotMon.live.data.analytics; 723 return me._pagesList.toSorted( (a, b) => { 724 return b.count - a.count; 725 }).slice(0,max); 726 }, 727 728 // Referer List: 729 _refererList: [], 730 731 addToRefererList: function(ref) { 732 //console.log('BotMon.live.data.analytics.addToRefererList',ref); 733 734 const me = BotMon.live.data.analytics; 735 736 // ignore internal references: 737 if (ref && ref.host == window.location.host) { 738 return; 739 } 740 741 const refInfo = me.getRefererInfo(ref); 742 743 // already exists? 744 let refObj = null; 745 for (let i = 0; i < me._refererList.length; i++) { 746 if (me._refererList[i].id == refInfo.id) { 747 refObj = me._refererList[i]; 748 break; 749 } 750 } 751 752 // if not exists, create it: 753 if (!refObj) { 754 refObj = refInfo; 755 refObj.count = 1; 756 me._refererList.push(refObj); 757 } else { 758 refObj.count += 1; 759 } 760 }, 761 762 getRefererInfo: function(url) { 763 //console.log('BotMon.live.data.analytics.getRefererInfo',url); 764 try { 765 url = new URL(url); 766 } catch (e) { 767 return { 768 'id': 'null', 769 'n': 'Invalid Referer' 770 }; 771 } 772 773 // find the referer ID: 774 let refId = 'null'; 775 let refName = 'No Referer'; 776 if (url && url.host) { 777 const hArr = url.host.split('.'); 778 const tld = hArr[hArr.length-1]; 779 refId = ( tld == 'localhost' ? tld : hArr[hArr.length-2]); 780 refName = hArr[hArr.length-2] + '.' + tld; 781 } 782 783 return { 784 'id': refId, 785 'n': refName 786 }; 787 }, 788 789 /** 790 * Get a sorted list of the top referers. 791 * The list is sorted in descending order of count. 792 * If the array has more items than the given maximum, the rest of the items are added to an "other" item. 793 * Each item in the list has a "pct" property, which is the percentage of the total count. 794 * @param {number} max - The maximum number of items to return. 795 * @return {Array} The sorted list of top referers. 796 */ 797 getTopReferers: function(max) { 798 //console.info(('BotMon.live.data.analytics.getTopReferers(' + max + ')')); 799 800 const me = BotMon.live.data.analytics; 801 802 return me._makeTopList(me._refererList, max); 803 }, 804 805 /** 806 * Create a sorted list of top items from a given array. 807 * The list is sorted in descending order of count. 808 * If the array has more items than the given maximum, the rest of the items are added to an "other" item. 809 * Each item in the list has a "pct" property, which is the percentage of the total count. 810 * @param {Array} arr - The array to sort and truncate. 811 * @param {number} max - The maximum number of items to return. 812 * @return {Array} The sorted list of top items. 813 */ 814 _makeTopList: function(arr, max) { 815 //console.info(('BotMon.live.data.analytics._makeTopList(arr,' + max + ')')); 816 817 const me = BotMon.live.data.analytics; 818 819 // sort the list: 820 arr.sort( (a,b) => { 821 return b.count - a.count; 822 }); 823 824 const rList = []; // return array 825 const max2 = ( arr.length >= max ? max-1 : arr.length ); 826 const other = { 827 'id': 'other', 828 'name': "Others", 829 'count': 0 830 }; 831 let total = 0; // adding up the items 832 for (let i=0; Math.min(max, arr.length) > i; i++) { 833 const it = arr[i]; 834 if (it) { 835 if (i < max2) { 836 const rIt = { 837 id: it.id, 838 name: (it.n ? it.n : it.id), 839 count: it.count 840 }; 841 rList.push(rIt); 842 } else { 843 other.count += it.count; 844 } 845 total += it.count; 846 } 847 } 848 849 // add the "other" item, if needed: 850 if (arr.length > max2) { 851 rList.push(other); 852 }; 853 854 rList.forEach( it => { 855 it.pct = (it.count * 100 / total); 856 }); 857 858 return rList; 859 }, 860 861 /* countries of visits */ 862 _countries: { 863 'human': [], 864 'bot': [] 865 }, 866 /** 867 * Adds a country code to the statistics. 868 * 869 * @param {string} iso The ISO 3166-1 alpha-2 country code. 870 */ 871 addToCountries: function(iso, name, type) { 872 873 const me = BotMon.live.data.analytics; 874 875 // find the correct array: 876 let arr = null; 877 switch (type) { 878 879 case BM_USERTYPE.KNOWN_USER: 880 case BM_USERTYPE.PROBABLY_HUMAN: 881 arr = me._countries.human; 882 break; 883 case BM_USERTYPE.LIKELY_BOT: 884 case BM_USERTYPE.KNOWN_BOT: 885 arr = me._countries.bot; 886 break; 887 default: 888 console.warn(`Unknown user type ${type} in function addToCountries.`); 889 } 890 891 if (arr) { 892 let cRec = arr.find( it => it.id == iso); 893 if (!cRec) { 894 cRec = { 895 'id': iso, 896 'n': name, 897 'count': 1 898 }; 899 arr.push(cRec); 900 } else { 901 cRec.count += 1; 902 } 903 } 904 }, 905 906 /** 907 * Returns a list of countries with visit counts, sorted by visit count in descending order. 908 * 909 * @param {BM_USERTYPE} type array of types type of visitors to return. 910 * @param {number} max The maximum number of entries to return. 911 * @return {Array} A list of objects with properties 'iso' (ISO 3166-1 alpha-2 country code) and 'count' (visit count). 912 */ 913 getCountryList: function(type, max) { 914 915 const me = BotMon.live.data.analytics; 916 917 // find the correct array: 918 let arr = null; 919 switch (type) { 920 921 case 'human': 922 arr = me._countries.human; 923 break; 924 case 'bot': 925 arr = me._countries.bot; 926 break; 927 default: 928 console.warn(`Unknown user type ${type} in function getCountryList.`); 929 return; 930 } 931 932 return me._makeTopList(arr, max); 933 }, 934 935 /* browser and platform of human visitors */ 936 _browsers: [], 937 _platforms: [], 938 939 addBrowserPlatform: function(visitor) { 940 //console.info('addBrowserPlatform', visitor); 941 942 const me = BotMon.live.data.analytics; 943 944 // add to browsers list: 945 let browserRec = ( visitor._client ? visitor._client : {'id': 'unknown'}); 946 if (visitor._client) { 947 let bRec = me._browsers.find( it => it.id == browserRec.id); 948 if (!bRec) { 949 bRec = { 950 id: browserRec.id, 951 n: browserRec.n, 952 count: 1 953 }; 954 me._browsers.push(bRec); 955 } else { 956 bRec.count += 1; 957 } 958 } 959 960 // add to platforms list: 961 let platformRec = ( visitor._platform ? visitor._platform : {'id': 'unknown'}); 962 if (visitor._platform) { 963 let pRec = me._platforms.find( it => it.id == platformRec.id); 964 if (!pRec) { 965 pRec = { 966 id: platformRec.id, 967 n: platformRec.n, 968 count: 1 969 }; 970 me._platforms.push(pRec); 971 } else { 972 pRec.count += 1; 973 } 974 } 975 976 }, 977 978 getTopBrowsers: function(max) { 979 980 const me = BotMon.live.data.analytics; 981 982 return me._makeTopList(me._browsers, max); 983 }, 984 985 getTopPlatforms: function(max) { 986 987 const me = BotMon.live.data.analytics; 988 989 return me._makeTopList(me._platforms, max); 990 }, 991 992 /* bounces are counted, not calculates: */ 993 getBounceCount: function(type) { 994 995 const me = BotMon.live.data.analytics; 996 var bounces = 0; 997 const list = me.groups[type]; 998 999 list.forEach(it => { 1000 bounces += (it._pageViews.length <= 1 ? 1 : 0); 1001 }); 1002 1003 return bounces; 1004 } 1005 }, 1006 1007 // information on "known bots": 1008 bots: { 1009 // loads the list of known bots from a JSON file: 1010 init: async function() { 1011 //console.info('BotMon.live.data.bots.init()'); 1012 1013 // Load the list of known bots: 1014 BotMon.live.gui.status.showBusy("Loading known bots …"); 1015 const url = BotMon._baseDir + 'config/known-bots.json'; 1016 try { 1017 const response = await fetch(url); 1018 if (!response.ok) { 1019 throw new Error(`${response.status} ${response.statusText}`); 1020 } 1021 1022 this._list = await response.json(); 1023 this._ready = true; 1024 1025 } catch (error) { 1026 BotMon.live.gui.status.setError("Error while loading the known bots file:", error.message); 1027 } finally { 1028 BotMon.live.gui.status.hideBusy("Status: Done."); 1029 BotMon.live.data._dispatch('bots') 1030 } 1031 }, 1032 1033 // returns bot info if the clientId matches a known bot, null otherwise: 1034 match: function(agent) { 1035 //console.info('BotMon.live.data.bots.match(',agent,')'); 1036 1037 const BotList = BotMon.live.data.bots._list; 1038 1039 // default is: not found! 1040 let botInfo = null; 1041 1042 if (!agent) return null; 1043 1044 // check for known bots: 1045 BotList.find(bot => { 1046 let r = false; 1047 for (let j=0; j<bot.rx.length; j++) { 1048 const rxr = agent.match(new RegExp(bot.rx[j])); 1049 if (rxr) { 1050 botInfo = { 1051 n : bot.n, 1052 id: bot.id, 1053 geo: (bot.geo ? bot.geo : null), 1054 url: bot.url, 1055 v: (rxr.length > 1 ? rxr[1] : -1) 1056 }; 1057 r = true; 1058 break; 1059 }; 1060 }; 1061 return r; 1062 }); 1063 1064 // check for unknown bots: 1065 if (!botInfo) { 1066 const botmatch = agent.match(/([\s\d\w\-]*bot|[\s\d\w\-]*crawler|[\s\d\w\-]*spider)[\/\s;\),\\.$]/i); 1067 if(botmatch) { 1068 botInfo = {'id': ( botmatch[1] || "other_" ), 'n': "Other" + ( botmatch[1] ? " (" + botmatch[1] + ")" : "" ) , "bot": botmatch[1] }; 1069 } 1070 } 1071 1072 //console.log("botInfo:", botInfo); 1073 return botInfo; 1074 }, 1075 1076 1077 // indicates if the list is loaded and ready to use: 1078 _ready: false, 1079 1080 // the actual bot list is stored here: 1081 _list: [] 1082 }, 1083 1084 // information on known clients (browsers): 1085 clients: { 1086 // loads the list of known clients from a JSON file: 1087 init: async function() { 1088 //console.info('BotMon.live.data.clients.init()'); 1089 1090 // Load the list of known bots: 1091 BotMon.live.gui.status.showBusy("Loading known clients"); 1092 const url = BotMon._baseDir + 'config/known-clients.json'; 1093 try { 1094 const response = await fetch(url); 1095 if (!response.ok) { 1096 throw new Error(`${response.status} ${response.statusText}`); 1097 } 1098 1099 BotMon.live.data.clients._list = await response.json(); 1100 BotMon.live.data.clients._ready = true; 1101 1102 } catch (error) { 1103 BotMon.live.gui.status.setError("Error while loading the known clients file: " + error.message); 1104 } finally { 1105 BotMon.live.gui.status.hideBusy("Status: Done."); 1106 BotMon.live.data._dispatch('clients') 1107 } 1108 }, 1109 1110 // returns bot info if the user-agent matches a known bot, null otherwise: 1111 match: function(agent) { 1112 //console.info('BotMon.live.data.clients.match(',agent,')'); 1113 1114 let match = {"n": "Unknown", "v": -1, "id": 'null'}; 1115 1116 if (agent) { 1117 BotMon.live.data.clients._list.find(client => { 1118 let r = false; 1119 for (let j=0; j<client.rx.length; j++) { 1120 const rxr = agent.match(new RegExp(client.rx[j])); 1121 if (rxr) { 1122 match.n = client.n; 1123 match.v = (rxr.length > 1 ? rxr[1] : -1); 1124 match.id = client.id || null; 1125 r = true; 1126 break; 1127 } 1128 } 1129 return r; 1130 }); 1131 } 1132 1133 //console.log(match) 1134 return match; 1135 }, 1136 1137 // return the browser name for a browser ID: 1138 getName: function(id) { 1139 const it = BotMon.live.data.clients._list.find(client => client.id == id); 1140 return ( it && it.n ? it.n : "Unknown"); //it.n; 1141 }, 1142 1143 // indicates if the list is loaded and ready to use: 1144 _ready: false, 1145 1146 // the actual bot list is stored here: 1147 _list: [] 1148 1149 }, 1150 1151 // information on known platforms (operating systems): 1152 platforms: { 1153 // loads the list of known platforms from a JSON file: 1154 init: async function() { 1155 //console.info('BotMon.live.data.platforms.init()'); 1156 1157 // Load the list of known bots: 1158 BotMon.live.gui.status.showBusy("Loading known platforms"); 1159 const url = BotMon._baseDir + 'config/known-platforms.json'; 1160 try { 1161 const response = await fetch(url); 1162 if (!response.ok) { 1163 throw new Error(`${response.status} ${response.statusText}`); 1164 } 1165 1166 BotMon.live.data.platforms._list = await response.json(); 1167 BotMon.live.data.platforms._ready = true; 1168 1169 } catch (error) { 1170 BotMon.live.gui.status.setError("Error while loading the known platforms file: " + error.message); 1171 } finally { 1172 BotMon.live.gui.status.hideBusy("Status: Done."); 1173 BotMon.live.data._dispatch('platforms') 1174 } 1175 }, 1176 1177 // returns bot info if the browser id matches a known platform: 1178 match: function(cid) { 1179 //console.info('BotMon.live.data.platforms.match(',cid,')'); 1180 1181 let match = {"n": "Unknown", "id": 'null'}; 1182 1183 if (cid) { 1184 BotMon.live.data.platforms._list.find(platform => { 1185 let r = false; 1186 for (let j=0; j<platform.rx.length; j++) { 1187 const rxr = cid.match(new RegExp(platform.rx[j])); 1188 if (rxr) { 1189 match.n = platform.n; 1190 match.v = (rxr.length > 1 ? rxr[1] : -1); 1191 match.id = platform.id || null; 1192 r = true; 1193 break; 1194 } 1195 } 1196 return r; 1197 }); 1198 } 1199 1200 return match; 1201 }, 1202 1203 // return the platform name for a given ID: 1204 getName: function(id) { 1205 const it = BotMon.live.data.platforms._list.find( pf => pf.id == id); 1206 return ( it ? it.n : 'Unknown' ); 1207 }, 1208 1209 1210 // indicates if the list is loaded and ready to use: 1211 _ready: false, 1212 1213 // the actual bot list is stored here: 1214 _list: [] 1215 1216 }, 1217 1218 // storage and functions for the known bot IP-Ranges: 1219 ipRanges: { 1220 1221 init: function() { 1222 //console.log('BotMon.live.data.ipRanges.init()'); 1223 // #TODO: Load from separate IP-Ranges file 1224 // load the rules file: 1225 const me = BotMon.live.data; 1226 1227 try { 1228 BotMon.live.data._loadSettingsFile(['user-ipranges', 'known-ipranges'], 1229 (json) => { 1230 1231 // groups can be just saved in the data structure: 1232 if (json.groups && json.groups.constructor.name == 'Array') { 1233 me.ipRanges._groups = json.groups; 1234 } 1235 1236 // groups can be just saved in the data structure: 1237 if (json.ranges && json.ranges.constructor.name == 'Array') { 1238 json.ranges.forEach(range => { 1239 me.ipRanges.add(range); 1240 }) 1241 } 1242 1243 // finished loading 1244 BotMon.live.gui.status.hideBusy("Status: Done."); 1245 BotMon.live.data._dispatch('ipranges') 1246 }); 1247 } catch (error) { 1248 BotMon.live.gui.status.setError("Error while loading the config file: " + error.message); 1249 } 1250 }, 1251 1252 // the actual bot list is stored here: 1253 _list: [], 1254 _groups: [], 1255 1256 add: function(data) { 1257 //console.log('BotMon.live.data.ipRanges.add(',data,')'); 1258 1259 const me = BotMon.live.data.ipRanges; 1260 1261 // convert IP address to easier comparable form: 1262 const ip2Num = BotMon.t._ip2Num; 1263 1264 let item = { 1265 'cidr': data.from.replaceAll(/::+/g, '::') + '/' + ( data.m ? data.m : '??' ), 1266 'from': ip2Num(data.from), 1267 'to': ip2Num(data.to), 1268 'm': data.m, 1269 'g': data.g 1270 }; 1271 me._list.push(item); 1272 1273 }, 1274 1275 getOwner: function(rangeInfo) { 1276 1277 const me = BotMon.live.data.ipRanges; 1278 1279 for (let i=0; i < me._groups.length; i++) { 1280 const it = me._groups[i]; 1281 if (it.id == rangeInfo.g) { 1282 return it.name; 1283 } 1284 } 1285 return `Unknown (“${rangeInfo.g})`; 1286 }, 1287 1288 match: function(ip) { 1289 //console.log('BotMon.live.data.ipRanges.match(',ip,')'); 1290 1291 const me = BotMon.live.data.ipRanges; 1292 1293 // convert IP address to easier comparable form: 1294 const ipNum = BotMon.t._ip2Num(ip); 1295 1296 for (let i=0; i < me._list.length; i++) { 1297 const ipRange = me._list[i]; 1298 1299 if (ipNum >= ipRange.from && ipNum <= ipRange.to) { 1300 return ipRange; 1301 } 1302 1303 }; 1304 return null; 1305 } 1306 }, 1307 1308 // storage for the rules and related functions 1309 rules: { 1310 1311 /** 1312 * Initializes the rules data. 1313 * 1314 * Loads the default config file and the user config file (if present). 1315 * The default config file is used if the user config file does not have a certain setting. 1316 * The user config file can override settings from the default config file. 1317 * 1318 * The rules are loaded from the `rules` property of the config files. 1319 * The IP ranges are loaded from the `ipRanges` property of the config files. 1320 * 1321 * If an error occurs while loading the config file, it is displayed in the status bar. 1322 * After the config file is loaded, the status bar is hidden. 1323 */ 1324 init: async function() { 1325 //console.info('BotMon.live.data.rules.init()'); 1326 1327 // Load the list of known bots: 1328 BotMon.live.gui.status.showBusy("Loading list of rules …"); 1329 1330 // load the rules file: 1331 const me = BotMon.live.data; 1332 1333 try { 1334 BotMon.live.data._loadSettingsFile(['user-config', 'default-config'], 1335 (json) => { 1336 1337 // override the threshold? 1338 if (json.threshold) me._threshold = json.threshold; 1339 1340 // set the rules list: 1341 if (json.rules && json.rules.constructor.name == 'Array') { 1342 me.rules._rulesList = json.rules; 1343 } 1344 1345 BotMon.live.gui.status.hideBusy("Status: Done."); 1346 BotMon.live.data._dispatch('rules') 1347 } 1348 ); 1349 } catch (error) { 1350 BotMon.live.gui.status.setError("Error while loading the config file: " + error.message); 1351 } 1352 }, 1353 1354 _rulesList: [], // list of rules to find out if a visitor is a bot 1355 _threshold: 100, // above this, it is considered a bot. 1356 1357 // returns a descriptive text for a rule id 1358 getRuleInfo: function(ruleId) { 1359 // console.info('getRuleInfo', ruleId); 1360 1361 // shortcut for neater code: 1362 const me = BotMon.live.data.rules; 1363 1364 for (let i=0; i<me._rulesList.length; i++) { 1365 const rule = me._rulesList[i]; 1366 if (rule.id == ruleId) { 1367 return rule; 1368 } 1369 } 1370 return null; 1371 1372 }, 1373 1374 // evaluate a visitor for lkikelihood of being a bot 1375 evaluate: function(visitor) { 1376 1377 // shortcut for neater code: 1378 const me = BotMon.live.data.rules; 1379 1380 let r = { // evaluation result 1381 'val': 0, 1382 'rules': [], 1383 'isBot': false 1384 }; 1385 1386 for (let i=0; i<me._rulesList.length; i++) { 1387 const rule = me._rulesList[i]; 1388 const params = ( rule.params ? rule.params : [] ); 1389 1390 if (rule.func) { // rule is calling a function 1391 if (me.func[rule.func]) { 1392 if(me.func[rule.func](visitor, ...params)) { 1393 r.val += rule.bot; 1394 r.rules.push(rule.id) 1395 } 1396 } else { 1397 //console.warn("Unknown rule function: “${rule.func}”. Ignoring rule.") 1398 } 1399 } 1400 } 1401 1402 // is a bot? 1403 r.isBot = (r.val >= me._threshold); 1404 1405 return r; 1406 }, 1407 1408 // list of functions that can be called by the rules list to evaluate a visitor: 1409 func: { 1410 1411 // check if client is on the list passed as parameter: 1412 matchesClient: function(visitor, ...clients) { 1413 1414 const clientId = ( visitor._client ? visitor._client.id : ''); 1415 return clients.includes(clientId); 1416 }, 1417 1418 // check if OS/Platform is one of the obsolete ones: 1419 matchesPlatform: function(visitor, ...platforms) { 1420 1421 const pId = ( visitor._platform ? visitor._platform.id : ''); 1422 1423 if (visitor._platform.id == null) console.log(visitor._platform); 1424 1425 return platforms.includes(pId); 1426 }, 1427 1428 // are there at lest num pages loaded? 1429 smallPageCount: function(visitor, num) { 1430 return (visitor._pageViews.length <= Number(num)); 1431 }, 1432 1433 // There was no entry in a specific log file for this visitor: 1434 // note that this will also trigger the "noJavaScript" rule: 1435 noRecord: function(visitor, type) { 1436 return !visitor._seenBy.includes(type); 1437 }, 1438 1439 // there are no referrers in any of the page visits: 1440 noReferrer: function(visitor) { 1441 1442 let r = false; // return value 1443 for (let i = 0; i < visitor._pageViews.length; i++) { 1444 if (!visitor._pageViews[i]._ref) { 1445 r = true; 1446 break; 1447 } 1448 } 1449 return r; 1450 }, 1451 1452 // test for specific client identifiers: 1453 /*matchesClients: function(visitor, ...list) { 1454 1455 for (let i=0; i<list.length; i++) { 1456 if (visitor._client.id == list[i]) { 1457 return true 1458 } 1459 }; 1460 return false; 1461 },*/ 1462 1463 // unusual combinations of Platform and Client: 1464 combinationTest: function(visitor, ...combinations) { 1465 1466 for (let i=0; i<combinations.length; i++) { 1467 1468 if (visitor._platform.id == combinations[i][0] 1469 && visitor._client.id == combinations[i][1]) { 1470 return true 1471 } 1472 }; 1473 1474 return false; 1475 }, 1476 1477 // is the IP address from a known bot network? 1478 fromKnownBotIP: function(visitor) { 1479 //console.info('fromKnownBotIP()', visitor.ip); 1480 1481 const ipInfo = BotMon.live.data.ipRanges.match(visitor.ip); 1482 1483 if (ipInfo) { 1484 visitor._ipInKnownBotRange = true; 1485 } 1486 1487 return (ipInfo !== null); 1488 }, 1489 1490 // is the page language mentioned in the client's accepted languages? 1491 // the parameter holds an array of exceptions, i.e. page languages that should be ignored. 1492 matchLang: function(visitor, ...exceptions) { 1493 1494 if (visitor.lang && visitor.accept && exceptions.indexOf(visitor.lang) < 0) { 1495 return (visitor.accept.split(',').indexOf(visitor.lang) < 0); 1496 } 1497 return false; 1498 }, 1499 1500 // the "Accept language" header contains certain entries: 1501 clientAccepts: function(visitor, ...languages) { 1502 //console.info('clientAccepts', visitor.accept, languages); 1503 1504 if (visitor.accept && languages) {; 1505 return ( visitor.accept.split(',').filter(lang => languages.includes(lang)).length > 0 ); 1506 } 1507 return false; 1508 }, 1509 1510 // Is there an accept-language field defined at all? 1511 noAcceptLang: function(visitor) { 1512 1513 if (!visitor.accept || visitor.accept.length <= 0) { // no accept-languages header 1514 return true; 1515 } 1516 // TODO: parametrize this! 1517 return false; 1518 }, 1519 // At least x page views were recorded, but they come within less than y seconds 1520 loadSpeed: function(visitor, minItems, maxTime) { 1521 1522 if (visitor._pageViews.length >= minItems) { 1523 //console.log('loadSpeed', visitor._pageViews.length, minItems, maxTime); 1524 1525 const pvArr = visitor._pageViews.map(pv => pv._lastSeen).sort(); 1526 1527 let totalTime = 0; 1528 for (let i=1; i < pvArr.length; i++) { 1529 totalTime += (pvArr[i] - pvArr[i-1]); 1530 } 1531 1532 //console.log(' ', totalTime , Math.round(totalTime / (pvArr.length * 1000)), (( totalTime / pvArr.length ) <= maxTime * 1000), visitor.ip); 1533 1534 return (( totalTime / pvArr.length ) <= maxTime * 1000); 1535 } 1536 }, 1537 1538 // Country code matches one of those in the list: 1539 matchesCountry: function(visitor, ...countries) { 1540 1541 // ingore if geoloc is not set or unknown: 1542 if (visitor.geo) { 1543 return (countries.indexOf(visitor.geo) >= 0); 1544 } 1545 return false; 1546 }, 1547 1548 // Country does not match one of the given codes. 1549 notFromCountry: function(visitor, ...countries) { 1550 1551 // ingore if geoloc is not set or unknown: 1552 if (visitor.geo && visitor.geo !== 'ZZ') { 1553 return (countries.indexOf(visitor.geo) < 0); 1554 } 1555 return false; 1556 } 1557 } 1558 }, 1559 1560 /** 1561 * Loads a settings file from the specified list of filenames. 1562 * If the file is successfully loaded, it will call the callback function 1563 * with the loaded JSON data. 1564 * If no file can be loaded, it will display an error message. 1565 * 1566 * @param {string[]} fns - list of filenames to load 1567 * @param {function} callback - function to call with the loaded JSON data 1568 */ 1569 _loadSettingsFile: async function(fns, callback) { 1570 //console.info('BotMon.live.data._loadSettingsFile()', fns); 1571 1572 const kJsonExt = '.json'; 1573 let loaded = false; // if successfully loaded file 1574 1575 for (let i=0; i<fns.length; i++) { 1576 const filename = fns[i] +kJsonExt; 1577 try { 1578 const response = await fetch(DOKU_BASE + 'lib/plugins/botmon/config/' + filename); 1579 if (!response.ok) { 1580 continue; 1581 } else { 1582 loaded = true; 1583 } 1584 const json = await response.json(); 1585 if (callback && typeof callback === 'function') { 1586 callback(json); 1587 } 1588 break; 1589 } catch (e) { 1590 BotMon.live.gui.status.setError("Error while loading the config file: " + filename); 1591 } 1592 } 1593 1594 if (!loaded) { 1595 BotMon.live.gui.status.setError("Could not load a config file."); 1596 } 1597 }, 1598 1599 /** 1600 * Loads a log file (server, page load, or ticker) and parses it. 1601 * @param {String} type - the type of the log file to load (srv, log, or tck) 1602 * @param {Function} [onLoaded] - an optional callback function to call after loading is finished. 1603 */ 1604 loadLogFile: async function(type, onLoaded = undefined) { 1605 //console.info('BotMon.live.data.loadLogFile(',type,')'); 1606 1607 let typeName = ''; 1608 let columns = []; 1609 1610 switch (type) { 1611 case "srv": 1612 typeName = "Server"; 1613 columns = ['ts','ip','pg','id','typ','usr','agent','ref','lang','accept','geo']; 1614 break; 1615 case "log": 1616 typeName = "Page load"; 1617 columns = ['ts','ip','pg','id','usr','lt','ref','agent']; 1618 break; 1619 case "tck": 1620 typeName = "Ticker"; 1621 columns = ['ts','ip','pg','id','agent']; 1622 break; 1623 default: 1624 console.warn(`Unknown log type ${type}.`); 1625 return; 1626 } 1627 1628 // Show the busy indicator and set the visible status: 1629 BotMon.live.gui.status.showBusy(`Loading ${typeName} log file …`); 1630 1631 // compose the URL from which to load: 1632 const url = BotMon._baseDir + `logs/${BotMon._datestr}.${type}.txt`; 1633 //console.log("Loading:",url); 1634 1635 // fetch the data: 1636 try { 1637 const response = await fetch(url); 1638 if (!response.ok) { 1639 1640 throw new Error(`${response.status} ${response.statusText}`); 1641 1642 } else { 1643 1644 // parse the data: 1645 const logtxt = await response.text(); 1646 if (logtxt.length <= 0) { 1647 throw new Error(`Empty log file ${url}.`); 1648 } 1649 1650 logtxt.split('\n').forEach((line) => { 1651 if (line.trim() === '') return; // skip empty lines 1652 const cols = line.split('\t'); 1653 1654 // assign the columns to an object: 1655 const data = {}; 1656 cols.forEach( (colVal,i) => { 1657 colName = columns[i] || `col${i}`; 1658 const colValue = (colName == 'ts' ? new Date(colVal) : colVal.trim()); 1659 data[colName] = colValue; 1660 }); 1661 1662 // register the visit in the model: 1663 switch(type) { 1664 case BM_LOGTYPE.SERVER: 1665 BotMon.live.data.model.registerVisit(data, type); 1666 break; 1667 case BM_LOGTYPE.CLIENT: 1668 data.typ = 'js'; 1669 BotMon.live.data.model.updateVisit(data); 1670 break; 1671 case BM_LOGTYPE.TICKER: 1672 data.typ = 'js'; 1673 BotMon.live.data.model.updateTicks(data); 1674 break; 1675 default: 1676 console.warn(`Unknown log type ${type}.`); 1677 return; 1678 } 1679 }); 1680 } 1681 1682 } catch (error) { 1683 BotMon.live.gui.status.setError(`Error while loading the ${typeName} log file: ${error.message} – data may be incomplete.`); 1684 } finally { 1685 BotMon.live.gui.status.hideBusy("Status: Done."); 1686 if (onLoaded) { 1687 onLoaded(); // callback after loading is finished. 1688 } 1689 } 1690 } 1691 }, 1692 1693 gui: { 1694 init: function() { 1695 // init the lists view: 1696 this.lists.init(); 1697 }, 1698 1699 /* The Overview / web metrics section of the live tab */ 1700 overview: { 1701 /** 1702 * Populates the overview part of the today tab with the analytics data. 1703 * 1704 * @method make 1705 * @memberof BotMon.live.gui.overview 1706 */ 1707 make: function() { 1708 1709 const data = BotMon.live.data.analytics.data; 1710 1711 const maxItemsPerList = 5; // how many list items to show? 1712 1713 // shortcut for neater code: 1714 const makeElement = BotMon.t._makeElement; 1715 1716 const botsVsHumans = document.getElementById('botmon__today__botsvshumans'); 1717 if (botsVsHumans) { 1718 botsVsHumans.appendChild(makeElement('dt', {}, "Bots’ metrics:")); 1719 1720 for (let i = 0; i <= 4; i++) { 1721 const dd = makeElement('dd'); 1722 let title = ''; 1723 let value = ''; 1724 switch(i) { 1725 case 0: 1726 title = "Page views by known bots:"; 1727 value = data.bots.known; 1728 break; 1729 case 1: 1730 title = "Page views by suspected bots:"; 1731 value = data.bots.suspected; 1732 break; 1733 case 2: 1734 title = "Page views by humans:"; 1735 value = data.bots.users + data.bots.human; 1736 break; 1737 case 3: 1738 title = "Total page views:"; 1739 value = data.totalPageViews; 1740 break; 1741 case 4: 1742 title = "Humans-to-bots ratio:"; 1743 value = BotMon.t._getRatio(data.bots.users + data.bots.human, data.bots.suspected + data.bots.known, 100); 1744 break; 1745 default: 1746 console.warn(`Unknown list type ${i}.`); 1747 } 1748 dd.appendChild(makeElement('span', {}, title)); 1749 dd.appendChild(makeElement('strong', {}, value)); 1750 botsVsHumans.appendChild(dd); 1751 } 1752 } 1753 1754 // update known bots list: 1755 const botElement = document.getElementById('botmon__botslist'); /* Known bots */ 1756 if (botElement) { 1757 botElement.innerHTML = `<dt>Top known bots:</dt>`; 1758 1759 let botList = BotMon.live.data.analytics.getTopBots(maxItemsPerList); 1760 botList.forEach( (botInfo) => { 1761 const bli = makeElement('dd'); 1762 bli.appendChild(makeElement('span', {'class': 'has_icon bot bot_' + botInfo.id }, botInfo.name)); 1763 bli.appendChild(makeElement('span', {'class': 'count' }, botInfo.count)); 1764 botElement.append(bli) 1765 }); 1766 } 1767 1768 // update the suspected bot IP ranges list: 1769 /*const botIps = document.getElementById('botmon__botips'); 1770 if (botIps) { 1771 botIps.appendChild(makeElement('dt', {}, "Bot IP ranges (top 5)")); 1772 1773 const ipList = BotMon.live.data.analytics.getTopBotIPRanges(5); 1774 ipList.forEach( (ipInfo) => { 1775 const li = makeElement('dd'); 1776 li.appendChild(makeElement('span', {'class': 'has_icon ipaddr ip' + ipInfo.typ }, ipInfo.ip)); 1777 li.appendChild(makeElement('span', {'class': 'count' }, ipInfo.num)); 1778 botIps.append(li) 1779 }); 1780 }*/ 1781 1782 // update the top bot countries list: 1783 const botCountries = document.getElementById('botmon__botcountries'); 1784 if (botCountries) { 1785 botCountries.appendChild(makeElement('dt', {}, `Top bot Countries:`)); 1786 const countryList = BotMon.live.data.analytics.getCountryList('bot', 5); 1787 countryList.forEach( (cInfo) => { 1788 const cLi = makeElement('dd'); 1789 cLi.appendChild(makeElement('span', {'class': 'has_icon country ctry_' + cInfo.id.toLowerCase() }, cInfo.name)); 1790 cLi.appendChild(makeElement('span', {'class': 'count' }, cInfo.count)); 1791 botCountries.appendChild(cLi); 1792 }); 1793 } 1794 1795 // update the webmetrics overview: 1796 const wmoverview = document.getElementById('botmon__today__wm_overview'); 1797 if (wmoverview) { 1798 1799 const humanVisits = BotMon.live.data.analytics.groups.users.length + BotMon.live.data.analytics.groups.humans.length; 1800 const bounceRate = Math.round(100 * (BotMon.live.data.analytics.getBounceCount('users') + BotMon.live.data.analytics.getBounceCount('humans')) / humanVisits); 1801 1802 wmoverview.appendChild(makeElement('dt', {}, "Humans’ metrics")); 1803 for (let i = 0; i <= 4; i++) { 1804 const dd = makeElement('dd'); 1805 let title = ''; 1806 let value = ''; 1807 switch(i) { 1808 case 0: 1809 title = "Page views by registered users:"; 1810 value = data.bots.users; 1811 break; 1812 case 1: 1813 title = "Page views by “probably humans”:"; 1814 value = data.bots.human; 1815 break; 1816 case 2: 1817 title = "Total human page views:"; 1818 value = data.bots.users + data.bots.human; 1819 break; 1820 case 3: 1821 title = "Total human visits:"; 1822 value = humanVisits; 1823 break; 1824 case 4: 1825 title = "Humans’ bounce rate:"; 1826 value = bounceRate + '%'; 1827 break; 1828 default: 1829 console.warn(`Unknown list type ${i}.`); 1830 } 1831 dd.appendChild(makeElement('span', {}, title)); 1832 dd.appendChild(makeElement('strong', {}, value)); 1833 wmoverview.appendChild(dd); 1834 } 1835 } 1836 1837 // update the webmetrics clients list: 1838 const wmclients = document.getElementById('botmon__today__wm_clients'); 1839 if (wmclients) { 1840 1841 wmclients.appendChild(makeElement('dt', {}, "Browsers")); 1842 1843 const clientList = BotMon.live.data.analytics.getTopBrowsers(maxItemsPerList); 1844 if (clientList) { 1845 clientList.forEach( (cInfo) => { 1846 const cDd = makeElement('dd'); 1847 cDd.appendChild(makeElement('span', {'class': 'has_icon client cl_' + cInfo.id }, ( cInfo.name ? cInfo.name : cInfo.id))); 1848 cDd.appendChild(makeElement('span', { 1849 'class': 'count', 1850 'title': cInfo.count + " page views" 1851 }, cInfo.pct.toFixed(1) + '%')); 1852 wmclients.appendChild(cDd); 1853 }); 1854 } 1855 } 1856 1857 // update the webmetrics platforms list: 1858 const wmplatforms = document.getElementById('botmon__today__wm_platforms'); 1859 if (wmplatforms) { 1860 1861 wmplatforms.appendChild(makeElement('dt', {}, "Platforms")); 1862 1863 const pfList = BotMon.live.data.analytics.getTopPlatforms(maxItemsPerList); 1864 if (pfList) { 1865 pfList.forEach( (pInfo) => { 1866 const pDd = makeElement('dd'); 1867 pDd.appendChild(makeElement('span', {'class': 'has_icon platform pf_' + pInfo.id }, ( pInfo.name ? pInfo.name : pInfo.id))); 1868 pDd.appendChild(makeElement('span', { 1869 'class': 'count', 1870 'title': pInfo.count + " page views" 1871 }, pInfo.pct.toFixed(1) + '%')); 1872 wmplatforms.appendChild(pDd); 1873 }); 1874 } 1875 } 1876 1877 // update the top bot countries list: 1878 const usrCountries = document.getElementById('botmon__today__wm_countries'); 1879 if (usrCountries) { 1880 usrCountries.appendChild(makeElement('dt', {}, `Top visitor Countries:`)); 1881 const usrCtryList = BotMon.live.data.analytics.getCountryList('human', 5); 1882 usrCtryList.forEach( (cInfo) => { 1883 const cLi = makeElement('dd'); 1884 cLi.appendChild(makeElement('span', {'class': 'has_icon country ctry_' + cInfo.id.toLowerCase() }, cInfo.name)); 1885 cLi.appendChild(makeElement('span', {'class': 'count' }, cInfo.count)); 1886 usrCountries.appendChild(cLi); 1887 }); 1888 } 1889 1890 // update the top pages; 1891 const wmpages = document.getElementById('botmon__today__wm_pages'); 1892 if (wmpages) { 1893 1894 wmpages.appendChild(makeElement('dt', {}, "Top pages")); 1895 1896 const pgList = BotMon.live.data.analytics.getTopPages(maxItemsPerList); 1897 if (pgList) { 1898 pgList.forEach( (pgInfo) => { 1899 const pgDd = makeElement('dd'); 1900 pgDd.appendChild(makeElement('a', { 1901 'class': 'page_icon', 1902 'href': DOKU_BASE + 'doku.php?id=' + encodeURIComponent(pgInfo.id), 1903 'target': 'preview', 1904 'title': "PageID: " + pgInfo.id 1905 }, pgInfo.id)); 1906 pgDd.appendChild(makeElement('span', { 1907 'class': 'count', 1908 'title': pgInfo.count + " page views" 1909 }, pgInfo.count)); 1910 wmpages.appendChild(pgDd); 1911 }); 1912 } 1913 } 1914 1915 // update the top referrers; 1916 const wmreferers = document.getElementById('botmon__today__wm_referers'); 1917 if (wmreferers) { 1918 1919 wmreferers.appendChild(makeElement('dt', {}, "Referers")); 1920 1921 const refList = BotMon.live.data.analytics.getTopReferers(maxItemsPerList); 1922 if (refList) { 1923 refList.forEach( (rInfo) => { 1924 const rDd = makeElement('dd'); 1925 rDd.appendChild(makeElement('span', {'class': 'has_icon referer ref_' + rInfo.id }, rInfo.name)); 1926 rDd.appendChild(makeElement('span', { 1927 'class': 'count', 1928 'title': rInfo.count + " references" 1929 }, rInfo.pct.toFixed(1) + '%')); 1930 wmreferers.appendChild(rDd); 1931 }); 1932 } 1933 } 1934 } 1935 }, 1936 1937 status: { 1938 setText: function(txt) { 1939 const el = document.getElementById('botmon__today__status'); 1940 if (el && BotMon.live.gui.status._errorCount <= 0) { 1941 el.innerText = txt; 1942 } 1943 }, 1944 1945 setTitle: function(html) { 1946 const el = document.getElementById('botmon__today__title'); 1947 if (el) { 1948 el.innerHTML = html; 1949 } 1950 }, 1951 1952 setError: function(txt) { 1953 console.error(txt); 1954 BotMon.live.gui.status._errorCount += 1; 1955 const el = document.getElementById('botmon__today__status'); 1956 if (el) { 1957 el.innerText = "Data may be incomplete."; 1958 el.classList.add('error'); 1959 } 1960 }, 1961 _errorCount: 0, 1962 1963 showBusy: function(txt = null) { 1964 BotMon.live.gui.status._busyCount += 1; 1965 const el = document.getElementById('botmon__today__busy'); 1966 if (el) { 1967 el.style.display = 'inline-block'; 1968 } 1969 if (txt) BotMon.live.gui.status.setText(txt); 1970 }, 1971 _busyCount: 0, 1972 1973 hideBusy: function(txt = null) { 1974 const el = document.getElementById('botmon__today__busy'); 1975 BotMon.live.gui.status._busyCount -= 1; 1976 if (BotMon.live.gui.status._busyCount <= 0) { 1977 if (el) el.style.display = 'none'; 1978 if (txt) BotMon.live.gui.status.setText(txt); 1979 } 1980 } 1981 }, 1982 1983 lists: { 1984 init: function() { 1985 1986 // function shortcut: 1987 const makeElement = BotMon.t._makeElement; 1988 1989 const parent = document.getElementById('botmon__today__visitorlists'); 1990 if (parent) { 1991 1992 for (let i=0; i < 4; i++) { 1993 1994 // change the id and title by number: 1995 let listTitle = ''; 1996 let listId = ''; 1997 let infolink = null; 1998 switch (i) { 1999 case 0: 2000 listTitle = "Registered users"; 2001 listId = 'users'; 2002 break; 2003 case 1: 2004 listTitle = "Probably humans"; 2005 listId = 'humans'; 2006 break; 2007 case 2: 2008 listTitle = "Suspected bots"; 2009 listId = 'suspectedBots'; 2010 infolink = 'https://leib.be/sascha/projects/dokuwiki/botmon/info/suspected_bots'; 2011 break; 2012 case 3: 2013 listTitle = "Known bots"; 2014 listId = 'knownBots'; 2015 infolink = 'https://leib.be/sascha/projects/dokuwiki/botmon/info/known_bots'; 2016 break; 2017 default: 2018 console.warn('Unknown list number.'); 2019 } 2020 2021 const details = makeElement('details', { 2022 'data-group': listId, 2023 'data-loaded': false 2024 }); 2025 const title = details.appendChild(makeElement('summary')); 2026 title.appendChild(makeElement('span', {'class': 'title'}, listTitle)); 2027 if (infolink) { 2028 title.appendChild(makeElement('a', { 2029 'class': 'ext_info', 2030 'target': '_blank', 2031 'href': infolink, 2032 'title': "More information" 2033 }, "Info")); 2034 } 2035 details.addEventListener("toggle", this._onDetailsToggle); 2036 2037 parent.appendChild(details); 2038 2039 } 2040 } 2041 }, 2042 2043 _onDetailsToggle: function(e) { 2044 //console.info('BotMon.live.gui.lists._onDetailsToggle()'); 2045 2046 const target = e.target; 2047 2048 if (target.getAttribute('data-loaded') == 'false') { // only if not loaded yet 2049 target.setAttribute('data-loaded', 'loading'); 2050 2051 const fillType = target.getAttribute('data-group'); 2052 const fillList = BotMon.live.data.analytics.groups[fillType]; 2053 if (fillList && fillList.length > 0) { 2054 2055 const ul = BotMon.t._makeElement('ul'); 2056 2057 fillList.forEach( (it) => { 2058 ul.appendChild(BotMon.live.gui.lists._makeVisitorItem(it, fillType)); 2059 }); 2060 2061 target.appendChild(ul); 2062 target.setAttribute('data-loaded', 'true'); 2063 } else { 2064 target.setAttribute('data-loaded', 'false'); 2065 } 2066 2067 } 2068 }, 2069 2070 _makeVisitorItem: function(data, type) { 2071 2072 // shortcut for neater code: 2073 const make = BotMon.t._makeElement; 2074 2075 let ipType = ( data.ip.indexOf(':') >= 0 ? '6' : '4' ); 2076 if (data.ip == '127.0.0.1' || data.ip == '::1' ) ipType = '0'; 2077 2078 const platformName = (data._platform ? data._platform.n : 'Unknown'); 2079 const clientName = (data._client ? data._client.n: 'Unknown'); 2080 2081 const sumClass = ( !data._seenBy || data._seenBy.indexOf(BM_LOGTYPE.SERVER) < 0 ? 'noServer' : 'hasServer'); 2082 2083 const li = make('li'); // root list item 2084 const details = make('details'); 2085 const summary = make('summary', { 2086 'class': sumClass 2087 }); 2088 details.appendChild(summary); 2089 2090 const span1 = make('span'); /* left-hand group */ 2091 2092 if (data._type !== BM_USERTYPE.KNOWN_BOT) { /* No platform/client for bots */ 2093 span1.appendChild(make('span', { /* Platform */ 2094 'class': 'icon_only platform pf_' + (data._platform ? data._platform.id : 'unknown'), 2095 'title': "Platform: " + platformName 2096 }, platformName)); 2097 2098 span1.appendChild(make('span', { /* Client */ 2099 'class': 'icon_only client client cl_' + (data._client ? data._client.id : 'unknown'), 2100 'title': "Client: " + clientName 2101 }, clientName)); 2102 } 2103 2104 // identifier: 2105 if (data._type == BM_USERTYPE.KNOWN_BOT) { /* Bot only */ 2106 2107 const botName = ( data._bot && data._bot.n ? data._bot.n : "Unknown"); 2108 span1.appendChild(make('span', { /* Bot */ 2109 'class': 'has_icon bot bot_' + (data._bot ? data._bot.id : 'unknown'), 2110 'title': "Bot: " + botName 2111 }, botName)); 2112 2113 } else if (data._type == BM_USERTYPE.KNOWN_USER) { /* User only */ 2114 2115 span1.appendChild(make('span', { /* User */ 2116 'class': 'has_icon user_known', 2117 'title': "User: " + data.usr 2118 }, data.usr)); 2119 2120 } else { /* others */ 2121 2122 2123 /*span1.appendChild(make('span', { // IP-Address 2124 'class': 'has_icon ipaddr ip' + ipType, 2125 'title': "IP-Address: " + data.ip 2126 }, data.ip));*/ 2127 2128 span1.appendChild(make('span', { /* Internal ID */ 2129 'class': 'has_icon session typ_' + data.typ, 2130 'title': "ID: " + data.id 2131 }, data.id)); 2132 } 2133 2134 // country flag: 2135 if (data.geo && data.geo !== 'ZZ') { 2136 span1.appendChild(make('span', { 2137 'class': 'icon_only country ctry_' + data.geo.toLowerCase(), 2138 'data-ctry': data.geo, 2139 'title': "Country: " + ( data._country || "Unknown") 2140 }, ( data._country || "Unknown") )); 2141 } 2142 2143 // referer icons: 2144 if ((data._type == BM_USERTYPE.PROBABLY_HUMAN || data._type == BM_USERTYPE.LIKELY_BOT) && data.ref) { 2145 const refInfo = BotMon.live.data.analytics.getRefererInfo(data.ref); 2146 span1.appendChild(make('span', { 2147 'class': 'icon_only referer ref_' + refInfo.id, 2148 'title': "Referer: " + data.ref 2149 }, refInfo.n)); 2150 } 2151 2152 summary.appendChild(span1); 2153 const span2 = make('span'); /* right-hand group */ 2154 2155 span2.appendChild(make('span', { /* first-seen */ 2156 'class': 'has_iconfirst-seen', 2157 'title': "First seen: " + data._firstSeen.toLocaleString() + " UTC" 2158 }, BotMon.t._formatTime(data._firstSeen))); 2159 2160 span2.appendChild(make('span', { /* page views */ 2161 'class': 'has_icon pageviews', 2162 'title': data._pageViews.length + " page view(s)" 2163 }, data._pageViews.length)); 2164 2165 summary.appendChild(span2); 2166 2167 // add details expandable section: 2168 details.appendChild(BotMon.live.gui.lists._makeVisitorDetails(data, type)); 2169 2170 li.appendChild(details); 2171 return li; 2172 }, 2173 2174 _makeVisitorDetails: function(data, type) { 2175 2176 // shortcut for neater code: 2177 const make = BotMon.t._makeElement; 2178 2179 let ipType = ( data.ip.indexOf(':') >= 0 ? '6' : '4' ); 2180 if (data.ip == '127.0.0.1' || data.ip == '::1' ) ipType = '0'; 2181 const platformName = (data._platform ? data._platform.n : 'Unknown'); 2182 const clientName = (data._client ? data._client.n: 'Unknown'); 2183 2184 const dl = make('dl', {'class': 'visitor_details'}); 2185 2186 if (data._type == BM_USERTYPE.KNOWN_BOT) { 2187 2188 dl.appendChild(make('dt', {}, "Bot name:")); /* bot info */ 2189 dl.appendChild(make('dd', {'class': 'icon_only bot bot_' + (data._bot ? data._bot.id : 'unknown')}, 2190 (data._bot ? data._bot.n : 'Unknown'))); 2191 2192 if (data._bot && data._bot.url) { 2193 dl.appendChild(make('dt', {}, "Bot info:")); /* bot info */ 2194 const botInfoDd = dl.appendChild(make('dd')); 2195 botInfoDd.appendChild(make('a', { 2196 'href': data._bot.url, 2197 'target': '_blank' 2198 }, data._bot.url)); /* bot info link*/ 2199 2200 } 2201 2202 } else { /* not for bots */ 2203 2204 dl.appendChild(make('dt', {}, "Client:")); /* client */ 2205 dl.appendChild(make('dd', {'class': 'has_icon client cl_' + (data._client ? data._client.id : 'unknown')}, 2206 clientName + ( data._client.v > 0 ? ' (' + data._client.v + ')' : '' ) )); 2207 2208 dl.appendChild(make('dt', {}, "Platform:")); /* platform */ 2209 dl.appendChild(make('dd', {'class': 'has_icon platform pf_' + (data._platform ? data._platform.id : 'unknown')}, 2210 platformName + ( data._platform.v > 0 ? ' (' + data._platform.v + ')' : '' ) )); 2211 2212 /*dl.appendChild(make('dt', {}, "ID:")); 2213 dl.appendChild(make('dd', {'class': 'has_icon ip' + data.typ}, data.id));*/ 2214 } 2215 2216 dl.appendChild(make('dt', {}, "IP-Address:")); 2217 const ipItem = make('dd', {'class': 'has_icon ipaddr ip' + ipType}); 2218 ipItem.appendChild(make('span', {'class': 'address'} , data.ip)); 2219 ipItem.appendChild(make('a', { 2220 'class': 'icon_only extlink ipinfo', 2221 'href': `https://ipinfo.io/${encodeURIComponent(data.ip)}`, 2222 'target': 'ipinfo', 2223 'title': "View this address on IPInfo.io" 2224 } , "DNS Info")); 2225 ipItem.appendChild(make('a', { 2226 'class': 'icon_only extlink abuseipdb', 2227 'href': `https://www.abuseipdb.com/check/${encodeURIComponent(data.ip)}`, 2228 'target': 'abuseipdb', 2229 'title': "Check this address on AbuseIPDB.com" 2230 } , "Check on AbuseIPDB")); 2231 dl.appendChild(ipItem); 2232 2233 if (Math.abs(data._lastSeen - data._firstSeen) < 100) { 2234 dl.appendChild(make('dt', {}, "Seen:")); 2235 dl.appendChild(make('dd', {'class': 'seen'}, data._firstSeen.toLocaleString())); 2236 } else { 2237 dl.appendChild(make('dt', {}, "First seen:")); 2238 dl.appendChild(make('dd', {'class': 'firstSeen'}, data._firstSeen.toLocaleString())); 2239 dl.appendChild(make('dt', {}, "Last seen:")); 2240 dl.appendChild(make('dd', {'class': 'lastSeen'}, data._lastSeen.toLocaleString())); 2241 } 2242 2243 dl.appendChild(make('dt', {}, "User-Agent:")); 2244 dl.appendChild(make('dd', {'class': 'agent'}, data.agent)); 2245 2246 dl.appendChild(make('dt', {}, "Languages:")); 2247 dl.appendChild(make('dd', {'class': 'langs'}, ` [${data.accept}]`)); 2248 2249 if (data.geo && data.geo !=='') { 2250 dl.appendChild(make('dt', {}, "Location:")); 2251 dl.appendChild(make('dd', { 2252 'class': 'has_icon country ctry_' + data.geo.toLowerCase(), 2253 'data-ctry': data.geo, 2254 'title': "Country: " + data._country 2255 }, data._country + ' (' + data.geo + ')')); 2256 } 2257 2258 dl.appendChild(make('dt', {}, "Session ID:")); 2259 dl.appendChild(make('dd', {'class': 'has_icon session typ_' + data.typ}, data.id)); 2260 2261 dl.appendChild(make('dt', {}, "Seen by:")); 2262 dl.appendChild(make('dd', undefined, data._seenBy.join(', ') )); 2263 2264 dl.appendChild(make('dt', {}, "Visited pages:")); 2265 const pagesDd = make('dd', {'class': 'pages'}); 2266 const pageList = make('ul'); 2267 2268 /* list all page views */ 2269 data._pageViews.sort( (a, b) => a._firstSeen - b._firstSeen ); 2270 data._pageViews.forEach( (page) => { 2271 pageList.appendChild(BotMon.live.gui.lists._makePageViewItem(page)); 2272 }); 2273 pagesDd.appendChild(pageList); 2274 dl.appendChild(pagesDd); 2275 2276 /* bot evaluation rating */ 2277 if (data._type !== BM_USERTYPE.KNOWN_BOT && data._type !== BM_USERTYPE.KNOWN_USER) { 2278 dl.appendChild(make('dt', undefined, "Bot rating:")); 2279 dl.appendChild(make('dd', {'class': 'bot-rating'}, ( data._botVal ? data._botVal : '–' ) + ' (of ' + BotMon.live.data.rules._threshold + ')')); 2280 2281 /* add bot evaluation details: */ 2282 if (data._eval) { 2283 dl.appendChild(make('dt', {}, "Bot evaluation:")); 2284 const evalDd = make('dd'); 2285 const testList = make('ul',{ 2286 'class': 'eval' 2287 }); 2288 data._eval.forEach( test => { 2289 2290 const tObj = BotMon.live.data.rules.getRuleInfo(test); 2291 let tDesc = tObj ? tObj.desc : test; 2292 2293 // special case for Bot IP range test: 2294 if (tObj.func == 'fromKnownBotIP') { 2295 const rangeInfo = BotMon.live.data.ipRanges.match(data.ip); 2296 if (rangeInfo) { 2297 const owner = BotMon.live.data.ipRanges.getOwner(rangeInfo); 2298 tDesc += ' (range: “' + rangeInfo.cidr + '”, ' + owner + ')'; 2299 } 2300 } 2301 2302 // create the entry field 2303 const tstLi = make('li'); 2304 tstLi.appendChild(make('span', { 2305 'data-testid': test 2306 }, tDesc)); 2307 tstLi.appendChild(make('span', {}, ( tObj ? tObj.bot : '—') )); 2308 testList.appendChild(tstLi); 2309 }); 2310 2311 // add total row 2312 const tst2Li = make('li', { 2313 'class': 'total' 2314 }); 2315 /*tst2Li.appendChild(make('span', {}, "Total:")); 2316 tst2Li.appendChild(make('span', {}, data._botVal)); 2317 testList.appendChild(tst2Li);*/ 2318 2319 evalDd.appendChild(testList); 2320 dl.appendChild(evalDd); 2321 } 2322 } 2323 // return the element to add to the UI: 2324 return dl; 2325 }, 2326 2327 // make a page view item: 2328 _makePageViewItem: function(page) { 2329 //console.log("makePageViewItem:",page); 2330 2331 // shortcut for neater code: 2332 const make = BotMon.t._makeElement; 2333 2334 // the actual list item: 2335 const pgLi = make('li'); 2336 2337 const row1 = make('div', {'class': 'row'}); 2338 2339 row1.appendChild(make('a', { // page id is the left group 2340 'href': DOKU_BASE + 'doku.php?id=' + encodeURIComponent(page.pg), 2341 'target': 'preview', 2342 'hreflang': page.lang, 2343 'title': "PageID: " + page.pg 2344 }, page.pg)); /* DW Page ID */ 2345 2346 // get the time difference: 2347 row1.appendChild(make('span', { 2348 'class': 'first-seen', 2349 'title': "First visited: " + page._firstSeen.toLocaleString() + " UTC" 2350 }, BotMon.t._formatTime(page._firstSeen))); 2351 2352 pgLi.appendChild(row1); 2353 2354 /* LINE 2 */ 2355 2356 const row2 = make('div', {'class': 'row'}); 2357 2358 // page referrer: 2359 if (page._ref) { 2360 row2.appendChild(make('span', { 2361 'class': 'referer', 2362 'title': "Referrer: " + page._ref.href 2363 }, page._ref.hostname)); 2364 } else { 2365 row2.appendChild(make('span', { 2366 'class': 'referer' 2367 }, "No referer")); 2368 } 2369 2370 // visit duration: 2371 let visitTimeStr = "Bounce"; 2372 const visitDuration = page._lastSeen.getTime() - page._firstSeen.getTime(); 2373 if (visitDuration > 0) { 2374 visitTimeStr = Math.floor(visitDuration / 1000) + "s"; 2375 } 2376 const tDiff = BotMon.t._formatTimeDiff(page._firstSeen, page._lastSeen); 2377 if (tDiff) { 2378 row2.appendChild(make('span', {'class': 'visit-length', 'title': 'Last seen: ' + page._lastSeen.toLocaleString()}, tDiff)); 2379 } else { 2380 row2.appendChild(make('span', { 2381 'class': 'bounce', 2382 'title': "Visitor bounced"}, "Bounce")); 2383 } 2384 2385 pgLi.appendChild(row2); 2386 2387 return pgLi; 2388 } 2389 } 2390 } 2391}; 2392 2393/* launch only if the BotMon admin panel is open: */ 2394if (document.getElementById('botmon__admin')) { 2395 BotMon.init(); 2396}