xref: /plugin/botmon/script.js (revision a93de874d554b3915acd2e069ef97a4cff9bb90a)
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						// add to the country lists:
618						me.addToCountries(v.geo, v._country, v._type);
619
620					} else { /* humans only */
621
622						// add browser and platform statistics:
623						me.addBrowserPlatform(v);
624
625						// add
626						v._pageViews.forEach( pv => {
627							me.addToRefererList(pv._ref);
628							me.addToPagesList(pv.pg);
629						});
630					}
631
632				});
633
634				BotMon.live.gui.status.hideBusy('Done.');
635			},
636
637			// get a list of known bots:
638			getTopBots: function(max) {
639				//console.info('BotMon.live.data.analytics.getTopBots('+max+')');
640
641				//console.log(BotMon.live.data.analytics.groups.knownBots);
642
643				let botsList = BotMon.live.data.analytics.groups.knownBots.toSorted( (a, b) => {
644					return b._pageViews.length - a._pageViews.length;
645				});
646
647				const other = {
648					'id': 'other',
649					'name': "Others",
650					'count': 0
651				};
652
653				const rList = [];
654				const max2 = ( botsList.length > max ? max-1 : botsList.length );
655				let total = 0; // adding up the items
656				for (let i=0; i<botsList.length; i++) {
657					const it = botsList[i];
658					if (it && it._bot) {
659						if (i < max2) {
660							rList.push({
661								id: it._bot.id,
662								name: (it._bot.n ? it._bot.n : it._bot.id),
663								count: it._pageViews.length
664							});
665						} else {
666							other.count += it._pageViews.length;
667						};
668						total += it._pageViews.length;
669					}
670				};
671
672				// add the "other" item, if needed:
673				if (botsList.length > max2) {
674					rList.push(other);
675				};
676
677				rList.forEach( it => {
678					it.pct = (it.count * 100 / total);
679				});
680
681				return rList;
682			},
683
684			// most visited pages list:
685			_pagesList: [],
686
687			/**
688			 * Add a page view to the list of most visited pages.
689			 * @param {string} pageId - The page ID to add to the list.
690			 * @example
691			 * BotMon.live.data.analytics.addToPagesList('1234567890');
692			 */
693			addToPagesList: function(pageId) {
694				//console.log('BotMon.live.data.analytics.addToPagesList', pageId);
695
696				const me = BotMon.live.data.analytics;
697
698				// already exists?
699				let pgObj = null;
700				for (let i = 0; i < me._pagesList.length; i++) {
701					if (me._pagesList[i].id == pageId) {
702						pgObj = me._pagesList[i];
703						break;
704					}
705				}
706
707				// if not exists, create it:
708				if (!pgObj) {
709					pgObj = {
710						id: pageId,
711						count: 1
712					};
713					me._pagesList.push(pgObj);
714				} else {
715					pgObj.count += 1;
716				}
717			},
718
719			getTopPages: function(max) {
720				//console.info('BotMon.live.data.analytics.getTopPages('+max+')');
721				const me = BotMon.live.data.analytics;
722				return me._pagesList.toSorted( (a, b) => {
723					return b.count - a.count;
724				}).slice(0,max);
725			},
726
727			// Referer List:
728			_refererList: [],
729
730			addToRefererList: function(ref) {
731				//console.log('BotMon.live.data.analytics.addToRefererList',ref);
732
733				const me = BotMon.live.data.analytics;
734
735				// ignore internal references:
736				if (ref && ref.host == window.location.host) {
737					return;
738				}
739
740				const refInfo = me.getRefererInfo(ref);
741
742				// already exists?
743				let refObj = null;
744				for (let i = 0; i < me._refererList.length; i++) {
745					if (me._refererList[i].id == refInfo.id) {
746						refObj = me._refererList[i];
747						break;
748					}
749				}
750
751				// if not exists, create it:
752				if (!refObj) {
753					refObj = refInfo;
754					refObj.count = 1;
755					me._refererList.push(refObj);
756				} else {
757					refObj.count += 1;
758				}
759			},
760
761			getRefererInfo: function(url) {
762				//console.log('BotMon.live.data.analytics.getRefererInfo',url);
763				try {
764					url = new URL(url);
765				} catch (e) {
766					return {
767						'id': 'null',
768						'n': 'Invalid Referer'
769					};
770				}
771
772				// find the referer ID:
773				let refId = 'null';
774				let refName = 'No Referer';
775				if (url && url.host) {
776					const hArr = url.host.split('.');
777					const tld = hArr[hArr.length-1];
778					refId = ( tld == 'localhost' ? tld : hArr[hArr.length-2]);
779					refName = hArr[hArr.length-2] + '.' + tld;
780				}
781
782				return {
783					'id': refId,
784					'n': refName
785				};
786			},
787
788			/**
789			 * Get a sorted list of the top referers.
790			 * The list is sorted in descending order of count.
791			 * If the array has more items than the given maximum, the rest of the items are added to an "other" item.
792			 * Each item in the list has a "pct" property, which is the percentage of the total count.
793			 * @param {number} max - The maximum number of items to return.
794			 * @return {Array} The sorted list of top referers.
795			 */
796			getTopReferers: function(max) {
797				//console.info(('BotMon.live.data.analytics.getTopReferers(' + max + ')'));
798
799				const me = BotMon.live.data.analytics;
800
801				return me._makeTopList(me._refererList, max);
802			},
803
804			/**
805			 * Create a sorted list of top items from a given array.
806			 * The list is sorted in descending order of count.
807			 * If the array has more items than the given maximum, the rest of the items are added to an "other" item.
808			 * Each item in the list has a "pct" property, which is the percentage of the total count.
809			 * @param {Array} arr - The array to sort and truncate.
810			 * @param {number} max - The maximum number of items to return.
811			 * @return {Array} The sorted list of top items.
812			 */
813			_makeTopList: function(arr, max) {
814				//console.info(('BotMon.live.data.analytics._makeTopList(arr,' + max + ')'));
815
816				const me = BotMon.live.data.analytics;
817
818				// sort the list:
819				arr.sort( (a,b) => {
820					return b.count - a.count;
821				});
822
823				const rList = []; // return array
824				const max2 = ( arr.length >= max ? max-1 : arr.length );
825				const other = {
826					'id': 'other',
827					'name': "Others",
828					'count': 0
829				};
830				let total = 0; // adding up the items
831				for (let i=0; Math.min(max, arr.length) > i; i++) {
832					const it = arr[i];
833					if (it) {
834						if (i < max2) {
835							const rIt = {
836								id: it.id,
837								name: (it.n ? it.n : it.id),
838								count: it.count
839							};
840							rList.push(rIt);
841						} else {
842							other.count += it.count;
843						}
844						total += it.count;
845					}
846				}
847
848				// add the "other" item, if needed:
849				if (arr.length > max2) {
850					rList.push(other);
851				};
852
853				rList.forEach( it => {
854					it.pct = (it.count * 100 / total);
855				});
856
857				return rList;
858			},
859
860			/* countries of visits */
861			_countries: {
862				'user': [],
863				'human': [],
864				'likelyBot': [],
865				'known_bot': []
866
867			},
868			/**
869			 * Adds a country code to the statistics.
870			 *
871			 * @param {string} iso The ISO 3166-1 alpha-2 country code.
872			 */
873			addToCountries: function(iso, name, type) {
874
875				const me = BotMon.live.data.analytics;
876
877				// find the correct array:
878				let arr = null;
879				switch (type) {
880
881					case BM_USERTYPE.KNOWN_USER:
882						arr = me._countries.user;
883						break;
884					case BM_USERTYPE.PROBABLY_HUMAN:
885						arr = me._countries.human;
886						break;
887					case BM_USERTYPE.LIKELY_BOT:
888						arr = me._countries.likelyBot;
889						break;
890					case BM_USERTYPE.KNOWN_BOT:
891						arr = me._countries.known_bot;
892						break;
893					default:
894						console.warn(`Unknown user type ${type} in function addToCountries.`);
895				}
896
897				if (arr) {
898					let cRec = arr.find( it => it.id == iso);
899					if (!cRec) {
900						cRec = {
901							'id': iso,
902							'n': name,
903							'count': 1
904						};
905						arr.push(cRec);
906					} else {
907						cRec.count += 1;
908					}
909				}
910			},
911
912			/**
913			 * Returns a list of countries with visit counts, sorted by visit count in descending order.
914			 *
915			 * @param {BM_USERTYPE} type The type of visitors to return.
916			 * @param {number} max The maximum number of entries to return.
917			 * @return {Array} A list of objects with properties 'iso' (ISO 3166-1 alpha-2 country code) and 'count' (visit count).
918			 */
919			getCountryList: function(type, max) {
920
921				const me = BotMon.live.data.analytics;
922
923				// find the correct array:
924				let arr = null;
925				switch (type) {
926
927					case BM_USERTYPE.KNOWN_USER:
928						arr = me._countries.user;
929						break;
930					case BM_USERTYPE.PROBABLY_HUMAN:
931						arr = me._countries.human;
932						break;
933					case BM_USERTYPE.LIKELY_BOT:
934						arr = me._countries.likelyBot;
935						break;
936					case BM_USERTYPE.KNOWN_BOT:
937						arr = me._countries.known_bot;
938						break;
939					default:
940						console.warn(`Unknown user type ${type} in function getCountryList.`);
941						return;
942				}
943
944				return me._makeTopList(arr, max);
945			},
946
947			/* browser and platform of human visitors */
948			_browsers: [],
949			_platforms: [],
950
951			addBrowserPlatform: function(visitor) {
952				//console.info('addBrowserPlatform', visitor);
953
954				const me = BotMon.live.data.analytics;
955
956				// add to browsers list:
957				let browserRec = ( visitor._client ? visitor._client : {'id': 'unknown'});
958				if (visitor._client) {
959					let bRec = me._browsers.find( it => it.id == browserRec.id);
960					if (!bRec) {
961						bRec = {
962							id: browserRec.id,
963							n: browserRec.n,
964							count: 1
965						};
966						me._browsers.push(bRec);
967					} else {
968						bRec.count += 1;
969					}
970				}
971
972				// add to platforms list:
973				let platformRec = ( visitor._platform ? visitor._platform : {'id': 'unknown'});
974				if (visitor._platform) {
975					let pRec = me._platforms.find( it => it.id == platformRec.id);
976					if (!pRec) {
977						pRec = {
978							id: platformRec.id,
979							n: platformRec.n,
980							count: 1
981						};
982						me._platforms.push(pRec);
983					} else {
984						pRec.count += 1;
985					}
986				}
987
988			},
989
990			getTopBrowsers: function(max) {
991
992				const me = BotMon.live.data.analytics;
993
994				return me._makeTopList(me._browsers, max);
995			},
996
997			getTopPlatforms: function(max) {
998
999				const me = BotMon.live.data.analytics;
1000
1001				return me._makeTopList(me._platforms, max);
1002			},
1003
1004			/* bounces are counted, not calculates: */
1005			getBounceCount: function(type) {
1006
1007				const me = BotMon.live.data.analytics;
1008				var bounces = 0;
1009				const list = me.groups[type];
1010
1011				list.forEach(it => {
1012					bounces += (it._pageViews.length <= 1 ? 1 : 0);
1013				});
1014
1015				return bounces;
1016			}
1017		},
1018
1019		// information on "known bots":
1020		bots: {
1021			// loads the list of known bots from a JSON file:
1022			init: async function() {
1023				//console.info('BotMon.live.data.bots.init()');
1024
1025				// Load the list of known bots:
1026				BotMon.live.gui.status.showBusy("Loading known bots …");
1027				const url = BotMon._baseDir + 'config/known-bots.json';
1028				try {
1029					const response = await fetch(url);
1030					if (!response.ok) {
1031						throw new Error(`${response.status} ${response.statusText}`);
1032					}
1033
1034					this._list = await response.json();
1035					this._ready = true;
1036
1037				} catch (error) {
1038					BotMon.live.gui.status.setError("Error while loading the known bots file:", error.message);
1039				} finally {
1040					BotMon.live.gui.status.hideBusy("Status: Done.");
1041					BotMon.live.data._dispatch('bots')
1042				}
1043			},
1044
1045			// returns bot info if the clientId matches a known bot, null otherwise:
1046			match: function(agent) {
1047				//console.info('BotMon.live.data.bots.match(',agent,')');
1048
1049				const BotList = BotMon.live.data.bots._list;
1050
1051				// default is: not found!
1052				let botInfo = null;
1053
1054				if (!agent) return null;
1055
1056				// check for known bots:
1057				BotList.find(bot => {
1058					let r = false;
1059					for (let j=0; j<bot.rx.length; j++) {
1060						const rxr = agent.match(new RegExp(bot.rx[j]));
1061						if (rxr) {
1062							botInfo = {
1063								n : bot.n,
1064								id: bot.id,
1065								geo: (bot.geo ? bot.geo : null),
1066								url: bot.url,
1067								v: (rxr.length > 1 ? rxr[1] : -1)
1068							};
1069							r = true;
1070							break;
1071						};
1072					};
1073					return r;
1074				});
1075
1076				// check for unknown bots:
1077				if (!botInfo) {
1078					const botmatch = agent.match(/([\s\d\w\-]*bot|[\s\d\w\-]*crawler|[\s\d\w\-]*spider)[\/\s;\),\\.$]/i);
1079					if(botmatch) {
1080						botInfo = {'id': ( botmatch[1] || "other_" ), 'n': "Other" + ( botmatch[1] ? " (" + botmatch[1] + ")" : "" ) , "bot": botmatch[1] };
1081					}
1082				}
1083
1084				//console.log("botInfo:", botInfo);
1085				return botInfo;
1086			},
1087
1088
1089			// indicates if the list is loaded and ready to use:
1090			_ready: false,
1091
1092			// the actual bot list is stored here:
1093			_list: []
1094		},
1095
1096		// information on known clients (browsers):
1097		clients: {
1098			// loads the list of known clients from a JSON file:
1099			init: async function() {
1100				//console.info('BotMon.live.data.clients.init()');
1101
1102				// Load the list of known bots:
1103				BotMon.live.gui.status.showBusy("Loading known clients");
1104				const url = BotMon._baseDir + 'config/known-clients.json';
1105				try {
1106					const response = await fetch(url);
1107					if (!response.ok) {
1108						throw new Error(`${response.status} ${response.statusText}`);
1109					}
1110
1111					BotMon.live.data.clients._list = await response.json();
1112					BotMon.live.data.clients._ready = true;
1113
1114				} catch (error) {
1115					BotMon.live.gui.status.setError("Error while loading the known clients file: " + error.message);
1116				} finally {
1117					BotMon.live.gui.status.hideBusy("Status: Done.");
1118					BotMon.live.data._dispatch('clients')
1119				}
1120			},
1121
1122			// returns bot info if the user-agent matches a known bot, null otherwise:
1123			match: function(agent) {
1124				//console.info('BotMon.live.data.clients.match(',agent,')');
1125
1126				let match = {"n": "Unknown", "v": -1, "id": 'null'};
1127
1128				if (agent) {
1129					BotMon.live.data.clients._list.find(client => {
1130						let r = false;
1131						for (let j=0; j<client.rx.length; j++) {
1132							const rxr = agent.match(new RegExp(client.rx[j]));
1133							if (rxr) {
1134								match.n = client.n;
1135								match.v = (rxr.length > 1 ? rxr[1] : -1);
1136								match.id = client.id || null;
1137								r = true;
1138								break;
1139							}
1140						}
1141						return r;
1142					});
1143				}
1144
1145				//console.log(match)
1146				return match;
1147			},
1148
1149			// return the browser name for a browser ID:
1150			getName: function(id) {
1151				const it = BotMon.live.data.clients._list.find(client => client.id == id);
1152				return ( it && it.n ? it.n : "Unknown"); //it.n;
1153			},
1154
1155			// indicates if the list is loaded and ready to use:
1156			_ready: false,
1157
1158			// the actual bot list is stored here:
1159			_list: []
1160
1161		},
1162
1163		// information on known platforms (operating systems):
1164		platforms: {
1165			// loads the list of known platforms from a JSON file:
1166			init: async function() {
1167				//console.info('BotMon.live.data.platforms.init()');
1168
1169				// Load the list of known bots:
1170				BotMon.live.gui.status.showBusy("Loading known platforms");
1171				const url = BotMon._baseDir + 'config/known-platforms.json';
1172				try {
1173					const response = await fetch(url);
1174					if (!response.ok) {
1175						throw new Error(`${response.status} ${response.statusText}`);
1176					}
1177
1178					BotMon.live.data.platforms._list = await response.json();
1179					BotMon.live.data.platforms._ready = true;
1180
1181				} catch (error) {
1182					BotMon.live.gui.status.setError("Error while loading the known platforms file: " + error.message);
1183				} finally {
1184					BotMon.live.gui.status.hideBusy("Status: Done.");
1185					BotMon.live.data._dispatch('platforms')
1186				}
1187			},
1188
1189			// returns bot info if the browser id matches a known platform:
1190			match: function(cid) {
1191				//console.info('BotMon.live.data.platforms.match(',cid,')');
1192
1193				let match = {"n": "Unknown", "id": 'null'};
1194
1195				if (cid) {
1196					BotMon.live.data.platforms._list.find(platform => {
1197						let r = false;
1198						for (let j=0; j<platform.rx.length; j++) {
1199							const rxr = cid.match(new RegExp(platform.rx[j]));
1200							if (rxr) {
1201								match.n = platform.n;
1202								match.v = (rxr.length > 1 ? rxr[1] : -1);
1203								match.id = platform.id || null;
1204								r = true;
1205								break;
1206							}
1207						}
1208						return r;
1209					});
1210				}
1211
1212				return match;
1213			},
1214
1215			// return the platform name for a given ID:
1216			getName: function(id) {
1217				const it = BotMon.live.data.platforms._list.find( pf => pf.id == id);
1218				return ( it ? it.n : 'Unknown' );
1219			},
1220
1221
1222			// indicates if the list is loaded and ready to use:
1223			_ready: false,
1224
1225			// the actual bot list is stored here:
1226			_list: []
1227
1228		},
1229
1230		// storage and functions for the known bot IP-Ranges:
1231		ipRanges: {
1232
1233			init: function() {
1234				//console.log('BotMon.live.data.ipRanges.init()');
1235				// #TODO: Load from separate IP-Ranges file
1236				// load the rules file:
1237				const me = BotMon.live.data;
1238
1239				try {
1240					BotMon.live.data._loadSettingsFile(['user-ipranges', 'known-ipranges'],
1241						(json) => {
1242
1243						// groups can be just saved in the data structure:
1244						if (json.groups && json.groups.constructor.name == 'Array') {
1245							me.ipRanges._groups = json.groups;
1246						}
1247
1248						// groups can be just saved in the data structure:
1249						if (json.ranges && json.ranges.constructor.name == 'Array') {
1250							json.ranges.forEach(range => {
1251								me.ipRanges.add(range);
1252							})
1253						}
1254
1255						// finished loading
1256						BotMon.live.gui.status.hideBusy("Status: Done.");
1257						BotMon.live.data._dispatch('ipranges')
1258					});
1259				} catch (error) {
1260					BotMon.live.gui.status.setError("Error while loading the config file: " + error.message);
1261				}
1262			},
1263
1264			// the actual bot list is stored here:
1265			_list: [],
1266			_groups: [],
1267
1268			add: function(data) {
1269				//console.log('BotMon.live.data.ipRanges.add(',data,')');
1270
1271				const me = BotMon.live.data.ipRanges;
1272
1273				// convert IP address to easier comparable form:
1274				const ip2Num = BotMon.t._ip2Num;
1275
1276				let item = {
1277					'cidr': data.from.replaceAll(/::+/g, '::') + '/' + ( data.m ? data.m : '??' ),
1278					'from': ip2Num(data.from),
1279					'to': ip2Num(data.to),
1280					'm': data.m,
1281					'g': data.g
1282				};
1283				me._list.push(item);
1284
1285			},
1286
1287			getOwner: function(rangeInfo) {
1288
1289				const me = BotMon.live.data.ipRanges;
1290
1291				for (let i=0; i < me._groups.length; i++) {
1292					const it = me._groups[i];
1293					if (it.id == rangeInfo.g) {
1294						return it.name;
1295					}
1296				}
1297				return `Unknown (“${rangeInfo.g})`;
1298			},
1299
1300			match: function(ip) {
1301				//console.log('BotMon.live.data.ipRanges.match(',ip,')');
1302
1303				const me = BotMon.live.data.ipRanges;
1304
1305				// convert IP address to easier comparable form:
1306				const ipNum = BotMon.t._ip2Num(ip);
1307
1308				for (let i=0; i < me._list.length; i++) {
1309					const ipRange = me._list[i];
1310
1311					if (ipNum >= ipRange.from && ipNum <= ipRange.to) {
1312						return ipRange;
1313					}
1314
1315				};
1316				return null;
1317			}
1318		},
1319
1320		// storage for the rules and related functions
1321		rules: {
1322
1323			/**
1324			 * Initializes the rules data.
1325			 *
1326			 * Loads the default config file and the user config file (if present).
1327			 * The default config file is used if the user config file does not have a certain setting.
1328			 * The user config file can override settings from the default config file.
1329			 *
1330			 * The rules are loaded from the `rules` property of the config files.
1331			 * The IP ranges are loaded from the `ipRanges` property of the config files.
1332			 *
1333			 * If an error occurs while loading the config file, it is displayed in the status bar.
1334			 * After the config file is loaded, the status bar is hidden.
1335			 */
1336			init: async function() {
1337				//console.info('BotMon.live.data.rules.init()');
1338
1339				// Load the list of known bots:
1340				BotMon.live.gui.status.showBusy("Loading list of rules …");
1341
1342				// load the rules file:
1343				const me = BotMon.live.data;
1344
1345				try {
1346					BotMon.live.data._loadSettingsFile(['user-config', 'default-config'],
1347						(json) => {
1348
1349							// override the threshold?
1350							if (json.threshold) me._threshold = json.threshold;
1351
1352							// set the rules list:
1353							if (json.rules && json.rules.constructor.name == 'Array') {
1354								me.rules._rulesList = json.rules;
1355							}
1356
1357							BotMon.live.gui.status.hideBusy("Status: Done.");
1358							BotMon.live.data._dispatch('rules')
1359						}
1360					);
1361				} catch (error) {
1362					BotMon.live.gui.status.setError("Error while loading the config file: " + error.message);
1363				}
1364			},
1365
1366			_rulesList: [], // list of rules to find out if a visitor is a bot
1367			_threshold: 100, // above this, it is considered a bot.
1368
1369			// returns a descriptive text for a rule id
1370			getRuleInfo: function(ruleId) {
1371				// console.info('getRuleInfo', ruleId);
1372
1373				// shortcut for neater code:
1374				const me = BotMon.live.data.rules;
1375
1376				for (let i=0; i<me._rulesList.length; i++) {
1377					const rule = me._rulesList[i];
1378					if (rule.id == ruleId) {
1379						return rule;
1380					}
1381				}
1382				return null;
1383
1384			},
1385
1386			// evaluate a visitor for lkikelihood of being a bot
1387			evaluate: function(visitor) {
1388
1389				// shortcut for neater code:
1390				const me = BotMon.live.data.rules;
1391
1392				let r =  {	// evaluation result
1393					'val': 0,
1394					'rules': [],
1395					'isBot': false
1396				};
1397
1398				for (let i=0; i<me._rulesList.length; i++) {
1399					const rule = me._rulesList[i];
1400					const params = ( rule.params ? rule.params : [] );
1401
1402					if (rule.func) { // rule is calling a function
1403						if (me.func[rule.func]) {
1404							if(me.func[rule.func](visitor, ...params)) {
1405								r.val += rule.bot;
1406								r.rules.push(rule.id)
1407							}
1408						} else {
1409							//console.warn("Unknown rule function: “${rule.func}”. Ignoring rule.")
1410						}
1411					}
1412				}
1413
1414				// is a bot?
1415				r.isBot = (r.val >= me._threshold);
1416
1417				return r;
1418			},
1419
1420			// list of functions that can be called by the rules list to evaluate a visitor:
1421			func: {
1422
1423				// check if client is on the list passed as parameter:
1424				matchesClient: function(visitor, ...clients) {
1425
1426					const clientId = ( visitor._client ? visitor._client.id : '');
1427					return clients.includes(clientId);
1428				},
1429
1430				// check if OS/Platform is one of the obsolete ones:
1431				matchesPlatform: function(visitor, ...platforms) {
1432
1433					const pId = ( visitor._platform ? visitor._platform.id : '');
1434
1435					if (visitor._platform.id == null) console.log(visitor._platform);
1436
1437					return platforms.includes(pId);
1438				},
1439
1440				// are there at lest num pages loaded?
1441				smallPageCount: function(visitor, num) {
1442					return (visitor._pageViews.length <= Number(num));
1443				},
1444
1445				// There was no entry in a specific log file for this visitor:
1446				// note that this will also trigger the "noJavaScript" rule:
1447				noRecord: function(visitor, type) {
1448					return !visitor._seenBy.includes(type);
1449				},
1450
1451				// there are no referrers in any of the page visits:
1452				noReferrer: function(visitor) {
1453
1454					let r = false; // return value
1455					for (let i = 0; i < visitor._pageViews.length; i++) {
1456						if (!visitor._pageViews[i]._ref) {
1457							r = true;
1458							break;
1459						}
1460					}
1461					return r;
1462				},
1463
1464				// test for specific client identifiers:
1465				/*matchesClients: function(visitor, ...list) {
1466
1467					for (let i=0; i<list.length; i++) {
1468						if (visitor._client.id == list[i]) {
1469								return true
1470						}
1471					};
1472					return false;
1473				},*/
1474
1475				// unusual combinations of Platform and Client:
1476				combinationTest: function(visitor, ...combinations) {
1477
1478					for (let i=0; i<combinations.length; i++) {
1479
1480						if (visitor._platform.id == combinations[i][0]
1481							&& visitor._client.id == combinations[i][1]) {
1482								return true
1483						}
1484					};
1485
1486					return false;
1487				},
1488
1489				// is the IP address from a known bot network?
1490				fromKnownBotIP: function(visitor) {
1491					//console.info('fromKnownBotIP()', visitor.ip);
1492
1493					const ipInfo = BotMon.live.data.ipRanges.match(visitor.ip);
1494
1495					if (ipInfo) {
1496						visitor._ipInKnownBotRange = true;
1497					}
1498
1499					return (ipInfo !== null);
1500				},
1501
1502				// is the page language mentioned in the client's accepted languages?
1503				// the parameter holds an array of exceptions, i.e. page languages that should be ignored.
1504				matchLang: function(visitor, ...exceptions) {
1505
1506					if (visitor.lang && visitor.accept && exceptions.indexOf(visitor.lang) < 0) {
1507						return (visitor.accept.split(',').indexOf(visitor.lang) < 0);
1508					}
1509					return false;
1510				},
1511
1512				// the "Accept language" header contains certain entries:
1513				clientAccepts: function(visitor, ...languages) {
1514					//console.info('clientAccepts', visitor.accept, languages);
1515
1516					if (visitor.accept && languages) {;
1517						return ( visitor.accept.split(',').filter(lang => languages.includes(lang)).length > 0 );
1518					}
1519					return false;
1520				},
1521
1522				// Is there an accept-language field defined at all?
1523				noAcceptLang: function(visitor) {
1524
1525					if (!visitor.accept || visitor.accept.length <= 0) { // no accept-languages header
1526						return true;
1527					}
1528					// TODO: parametrize this!
1529					return false;
1530				},
1531				// At least x page views were recorded, but they come within less than y seconds
1532				loadSpeed: function(visitor, minItems, maxTime) {
1533
1534					if (visitor._pageViews.length >= minItems) {
1535						//console.log('loadSpeed', visitor._pageViews.length, minItems, maxTime);
1536
1537						const pvArr = visitor._pageViews.map(pv => pv._lastSeen).sort();
1538
1539						let totalTime = 0;
1540						for (let i=1; i < pvArr.length; i++) {
1541							totalTime += (pvArr[i] - pvArr[i-1]);
1542						}
1543
1544						//console.log('     ', totalTime , Math.round(totalTime / (pvArr.length * 1000)), (( totalTime / pvArr.length ) <= maxTime * 1000), visitor.ip);
1545
1546						return (( totalTime / pvArr.length ) <= maxTime * 1000);
1547					}
1548				},
1549
1550				// Country code matches one of those in the list:
1551				matchesCountry: function(visitor, ...countries) {
1552
1553					// ingore if geoloc is not set or unknown:
1554					if (visitor.geo) {
1555						return (countries.indexOf(visitor.geo) >= 0);
1556					}
1557					return false;
1558				},
1559
1560				// Country does not match one of the given codes.
1561				notFromCountry: function(visitor, ...countries) {
1562
1563					// ingore if geoloc is not set or unknown:
1564					if (visitor.geo && visitor.geo !== 'ZZ') {
1565						return (countries.indexOf(visitor.geo) < 0);
1566					}
1567					return false;
1568				}
1569			}
1570		},
1571
1572		/**
1573		 * Loads a settings file from the specified list of filenames.
1574		 * If the file is successfully loaded, it will call the callback function
1575		 * with the loaded JSON data.
1576		 * If no file can be loaded, it will display an error message.
1577		 *
1578		 * @param {string[]} fns - list of filenames to load
1579		 * @param {function} callback - function to call with the loaded JSON data
1580		 */
1581		_loadSettingsFile: async function(fns, callback) {
1582			//console.info('BotMon.live.data._loadSettingsFile()', fns);
1583
1584			const kJsonExt = '.json';
1585			let loaded = false; // if successfully loaded file
1586
1587			for (let i=0; i<fns.length; i++) {
1588				const filename = fns[i] +kJsonExt;
1589				try {
1590					const response = await fetch(DOKU_BASE + 'lib/plugins/botmon/config/' + filename);
1591					if (!response.ok) {
1592						continue;
1593					} else {
1594						loaded = true;
1595					}
1596					const json = await response.json();
1597					if (callback && typeof callback === 'function') {
1598						callback(json);
1599					}
1600					break;
1601				} catch (e) {
1602					BotMon.live.gui.status.setError("Error while loading the config file: " + filename);
1603				}
1604			}
1605
1606			if (!loaded) {
1607				BotMon.live.gui.status.setError("Could not load a config file.");
1608			}
1609		},
1610
1611		/**
1612		 * Loads a log file (server, page load, or ticker) and parses it.
1613		 * @param {String} type - the type of the log file to load (srv, log, or tck)
1614		 * @param {Function} [onLoaded] - an optional callback function to call after loading is finished.
1615		 */
1616		loadLogFile: async function(type, onLoaded = undefined) {
1617			//console.info('BotMon.live.data.loadLogFile(',type,')');
1618
1619			let typeName = '';
1620			let columns = [];
1621
1622			switch (type) {
1623				case "srv":
1624					typeName = "Server";
1625					columns = ['ts','ip','pg','id','typ','usr','agent','ref','lang','accept','geo'];
1626					break;
1627				case "log":
1628					typeName = "Page load";
1629					columns = ['ts','ip','pg','id','usr','lt','ref','agent'];
1630					break;
1631				case "tck":
1632					typeName = "Ticker";
1633					columns = ['ts','ip','pg','id','agent'];
1634					break;
1635				default:
1636					console.warn(`Unknown log type ${type}.`);
1637					return;
1638			}
1639
1640			// Show the busy indicator and set the visible status:
1641			BotMon.live.gui.status.showBusy(`Loading ${typeName} log file …`);
1642
1643			// compose the URL from which to load:
1644			const url = BotMon._baseDir + `logs/${BotMon._datestr}.${type}.txt`;
1645			//console.log("Loading:",url);
1646
1647			// fetch the data:
1648			try {
1649				const response = await fetch(url);
1650				if (!response.ok) {
1651
1652					throw new Error(`${response.status} ${response.statusText}`);
1653
1654				} else {
1655
1656					// parse the data:
1657					const logtxt = await response.text();
1658					if (logtxt.length <= 0) {
1659						throw new Error(`Empty log file ${url}.`);
1660					}
1661
1662					logtxt.split('\n').forEach((line) => {
1663						if (line.trim() === '') return; // skip empty lines
1664						const cols = line.split('\t');
1665
1666						// assign the columns to an object:
1667						const data = {};
1668						cols.forEach( (colVal,i) => {
1669							colName = columns[i] || `col${i}`;
1670							const colValue = (colName == 'ts' ? new Date(colVal) : colVal.trim());
1671							data[colName] = colValue;
1672						});
1673
1674						// register the visit in the model:
1675						switch(type) {
1676							case BM_LOGTYPE.SERVER:
1677								BotMon.live.data.model.registerVisit(data, type);
1678								break;
1679							case BM_LOGTYPE.CLIENT:
1680								data.typ = 'js';
1681								BotMon.live.data.model.updateVisit(data);
1682								break;
1683							case BM_LOGTYPE.TICKER:
1684								data.typ = 'js';
1685								BotMon.live.data.model.updateTicks(data);
1686								break;
1687							default:
1688								console.warn(`Unknown log type ${type}.`);
1689								return;
1690						}
1691					});
1692				}
1693
1694			} catch (error) {
1695				BotMon.live.gui.status.setError(`Error while loading the ${typeName} log file: ${error.message} – data may be incomplete.`);
1696			} finally {
1697				BotMon.live.gui.status.hideBusy("Status: Done.");
1698				if (onLoaded) {
1699					onLoaded(); // callback after loading is finished.
1700				}
1701			}
1702		}
1703	},
1704
1705	gui: {
1706		init: function() {
1707			// init the lists view:
1708			this.lists.init();
1709		},
1710
1711		/* The Overview / web metrics section of the live tab */
1712		overview: {
1713			/**
1714			 * Populates the overview part of the today tab with the analytics data.
1715			 *
1716			 * @method make
1717			 * @memberof BotMon.live.gui.overview
1718			 */
1719			make: function() {
1720
1721				const data = BotMon.live.data.analytics.data;
1722
1723				const maxItemsPerList = 5; // how many list items to show?
1724
1725				// shortcut for neater code:
1726				const makeElement = BotMon.t._makeElement;
1727
1728				const botsVsHumans = document.getElementById('botmon__today__botsvshumans');
1729				if (botsVsHumans) {
1730					botsVsHumans.appendChild(makeElement('dt', {}, "Bots’ metrics:"));
1731
1732					for (let i = 0; i <= 4; i++) {
1733						const dd = makeElement('dd');
1734						let title = '';
1735						let value = '';
1736						switch(i) {
1737							case 0:
1738								title = "Page views by known bots:";
1739								value = data.bots.known;
1740								break;
1741							case 1:
1742								title = "Page views by suspected bots:";
1743								value = data.bots.suspected;
1744								break;
1745							case 2:
1746								title = "Page views by humans:";
1747								value = data.bots.users + data.bots.human;
1748								break;
1749							case 3:
1750								title = "Total page views:";
1751								value = data.totalPageViews;
1752								break;
1753							case 4:
1754								title = "Humans-to-bots ratio:";
1755								value = BotMon.t._getRatio(data.bots.users + data.bots.human, data.bots.suspected + data.bots.known, 100);
1756								break;
1757							default:
1758								console.warn(`Unknown list type ${i}.`);
1759						}
1760						dd.appendChild(makeElement('span', {}, title));
1761						dd.appendChild(makeElement('strong', {}, value));
1762						botsVsHumans.appendChild(dd);
1763					}
1764				}
1765
1766				// update known bots list:
1767				const botElement = document.getElementById('botmon__botslist'); /* Known bots */
1768				if (botElement) {
1769					botElement.innerHTML = `<dt>Top known bots:</dt>`;
1770
1771					let botList = BotMon.live.data.analytics.getTopBots(maxItemsPerList);
1772					botList.forEach( (botInfo) => {
1773						const bli = makeElement('dd');
1774						bli.appendChild(makeElement('span', {'class': 'has_icon bot bot_' + botInfo.id }, botInfo.name));
1775						bli.appendChild(makeElement('span', {'class': 'count' }, botInfo.count));
1776						botElement.append(bli)
1777					});
1778				}
1779
1780				// update the suspected bot IP ranges list:
1781				/*const botIps = document.getElementById('botmon__today__botips');
1782				if (botIps) {
1783					botIps.appendChild(makeElement('dt', {}, "Bot IP ranges (top 5)"));
1784
1785					const ipList = BotMon.live.data.analytics.getTopBotIPRanges(5);
1786					ipList.forEach( (ipInfo) => {
1787						const li = makeElement('dd');
1788						li.appendChild(makeElement('span', {'class': 'has_icon ipaddr ip' + ipInfo.typ }, ipInfo.ip));
1789						li.appendChild(makeElement('span', {'class': 'count' }, ipInfo.num));
1790						botIps.append(li)
1791					});
1792				}*/
1793
1794				// update the top bot countries list:
1795				const botCountries = document.getElementById('botmon__today__countries');
1796				if (botCountries) {
1797					botCountries.appendChild(makeElement('dt', {}, `Top bot Countries:`));
1798					const countryList = BotMon.live.data.analytics.getCountryList('likely_bot', 5);
1799					countryList.forEach( (cInfo) => {
1800						const cLi = makeElement('dd');
1801						cLi.appendChild(makeElement('span', {'class': 'has_icon country ctry_' + cInfo.id.toLowerCase() }, cInfo.name));
1802						cLi.appendChild(makeElement('span', {'class': 'count' }, cInfo.count));
1803						botCountries.appendChild(cLi);
1804					});
1805				}
1806
1807				// update the webmetrics overview:
1808				const wmoverview = document.getElementById('botmon__today__wm_overview');
1809				if (wmoverview) {
1810
1811					const humanVisits = BotMon.live.data.analytics.groups.users.length + BotMon.live.data.analytics.groups.humans.length;
1812					const bounceRate = Math.round(100 * (BotMon.live.data.analytics.getBounceCount('users') + BotMon.live.data.analytics.getBounceCount('humans')) / humanVisits);
1813
1814					wmoverview.appendChild(makeElement('dt', {}, "Humans’ metrics"));
1815					for (let i = 0; i <= 4; i++) {
1816						const dd = makeElement('dd');
1817						let title = '';
1818						let value = '';
1819						switch(i) {
1820							case 0:
1821								title = "Page views by registered users:";
1822								value = data.bots.users;
1823								break;
1824							case 1:
1825								title = "Page views by “probably humans”:";
1826								value = data.bots.human;
1827								break;
1828							case 2:
1829								title = "Total human page views:";
1830								value = data.bots.users + data.bots.human;
1831								break;
1832							case 3:
1833								title = "Total human visits:";
1834								value = humanVisits;
1835								break;
1836							case 4:
1837								title = "Humans’ bounce rate:";
1838								value = bounceRate + '%';
1839								break;
1840							default:
1841								console.warn(`Unknown list type ${i}.`);
1842						}
1843						dd.appendChild(makeElement('span', {}, title));
1844						dd.appendChild(makeElement('strong', {}, value));
1845						wmoverview.appendChild(dd);
1846					}
1847				}
1848
1849				// update the webmetrics clients list:
1850				const wmclients = document.getElementById('botmon__today__wm_clients');
1851				if (wmclients) {
1852
1853					wmclients.appendChild(makeElement('dt', {}, "Browsers"));
1854
1855					const clientList = BotMon.live.data.analytics.getTopBrowsers(maxItemsPerList);
1856					if (clientList) {
1857						clientList.forEach( (cInfo) => {
1858							const cDd = makeElement('dd');
1859							cDd.appendChild(makeElement('span', {'class': 'has_icon client cl_' + cInfo.id }, ( cInfo.name ? cInfo.name : cInfo.id)));
1860							cDd.appendChild(makeElement('span', {
1861								'class': 'count',
1862								'title': cInfo.count + " page views"
1863							}, cInfo.pct.toFixed(1) + '%'));
1864							wmclients.appendChild(cDd);
1865						});
1866					}
1867				}
1868
1869				// update the webmetrics platforms list:
1870				const wmplatforms = document.getElementById('botmon__today__wm_platforms');
1871				if (wmplatforms) {
1872
1873					wmplatforms.appendChild(makeElement('dt', {}, "Platforms"));
1874
1875					const pfList = BotMon.live.data.analytics.getTopPlatforms(maxItemsPerList);
1876					if (pfList) {
1877						pfList.forEach( (pInfo) => {
1878							const pDd = makeElement('dd');
1879							pDd.appendChild(makeElement('span', {'class': 'has_icon platform pf_' + pInfo.id }, ( pInfo.name ? pInfo.name : pInfo.id)));
1880							pDd.appendChild(makeElement('span', {
1881								'class': 'count',
1882								'title': pInfo.count + " page views"
1883							}, pInfo.pct.toFixed(1) + '%'));
1884							wmplatforms.appendChild(pDd);
1885						});
1886					}
1887				}
1888
1889				// update the top pages;
1890				const wmpages = document.getElementById('botmon__today__wm_pages');
1891				if (wmpages) {
1892
1893					wmpages.appendChild(makeElement('dt', {}, "Top pages"));
1894
1895					const pgList = BotMon.live.data.analytics.getTopPages(maxItemsPerList);
1896					if (pgList) {
1897						pgList.forEach( (pgInfo) => {
1898							const pgDd = makeElement('dd');
1899							pgDd.appendChild(makeElement('a', {
1900								'class': 'page_icon',
1901								'href': DOKU_BASE + 'doku.php?id=' + encodeURIComponent(pgInfo.id),
1902								'target': 'preview',
1903								'title': "PageID: " + pgInfo.id
1904							}, pgInfo.id));
1905							pgDd.appendChild(makeElement('span', {
1906								'class': 'count',
1907								'title': pgInfo.count + " page views"
1908							}, pgInfo.count));
1909							wmpages.appendChild(pgDd);
1910						});
1911					}
1912				}
1913
1914				// update the top referrers;
1915				const wmreferers = document.getElementById('botmon__today__wm_referers');
1916				if (wmreferers) {
1917
1918					wmreferers.appendChild(makeElement('dt', {}, "Referers"));
1919
1920					const refList = BotMon.live.data.analytics.getTopReferers(maxItemsPerList);
1921					if (refList) {
1922						refList.forEach( (rInfo) => {
1923							const rDd = makeElement('dd');
1924							rDd.appendChild(makeElement('span', {'class': 'has_icon referer ref_' + rInfo.id }, rInfo.name));
1925							rDd.appendChild(makeElement('span', {
1926								'class': 'count',
1927								'title': rInfo.count + " references"
1928							}, rInfo.pct.toFixed(1) + '%'));
1929							wmreferers.appendChild(rDd);
1930						});
1931					}
1932				}
1933			}
1934		},
1935
1936		status: {
1937			setText: function(txt) {
1938				const el = document.getElementById('botmon__today__status');
1939				if (el && BotMon.live.gui.status._errorCount <= 0) {
1940					el.innerText = txt;
1941				}
1942			},
1943
1944			setTitle: function(html) {
1945				const el = document.getElementById('botmon__today__title');
1946				if (el) {
1947					el.innerHTML = html;
1948				}
1949			},
1950
1951			setError: function(txt) {
1952				console.error(txt);
1953				BotMon.live.gui.status._errorCount += 1;
1954				const el = document.getElementById('botmon__today__status');
1955				if (el) {
1956					el.innerText = "Data may be incomplete.";
1957					el.classList.add('error');
1958				}
1959			},
1960			_errorCount: 0,
1961
1962			showBusy: function(txt = null) {
1963				BotMon.live.gui.status._busyCount += 1;
1964				const el = document.getElementById('botmon__today__busy');
1965				if (el) {
1966					el.style.display = 'inline-block';
1967				}
1968				if (txt) BotMon.live.gui.status.setText(txt);
1969			},
1970			_busyCount: 0,
1971
1972			hideBusy: function(txt = null) {
1973				const el = document.getElementById('botmon__today__busy');
1974				BotMon.live.gui.status._busyCount -= 1;
1975				if (BotMon.live.gui.status._busyCount <= 0) {
1976					if (el) el.style.display = 'none';
1977					if (txt) BotMon.live.gui.status.setText(txt);
1978				}
1979			}
1980		},
1981
1982		lists: {
1983			init: function() {
1984
1985				// function shortcut:
1986				const makeElement = BotMon.t._makeElement;
1987
1988				const parent = document.getElementById('botmon__today__visitorlists');
1989				if (parent) {
1990
1991					for (let i=0; i < 4; i++) {
1992
1993						// change the id and title by number:
1994						let listTitle = '';
1995						let listId = '';
1996						let infolink = null;
1997						switch (i) {
1998							case 0:
1999								listTitle = "Registered users";
2000								listId = 'users';
2001								break;
2002							case 1:
2003								listTitle = "Probably humans";
2004								listId = 'humans';
2005								break;
2006							case 2:
2007								listTitle = "Suspected bots";
2008								listId = 'suspectedBots';
2009								infolink = 'https://leib.be/sascha/projects/dokuwiki/botmon/info/suspected_bots';
2010								break;
2011							case 3:
2012								listTitle = "Known bots";
2013								listId = 'knownBots';
2014								infolink = 'https://leib.be/sascha/projects/dokuwiki/botmon/info/known_bots';
2015								break;
2016							default:
2017								console.warn('Unknown list number.');
2018						}
2019
2020						const details = makeElement('details', {
2021							'data-group': listId,
2022							'data-loaded': false
2023						});
2024						const title = details.appendChild(makeElement('summary'));
2025						title.appendChild(makeElement('span', {'class': 'title'}, listTitle));
2026						if (infolink) {
2027							title.appendChild(makeElement('a', {
2028								'class': 'ext_info',
2029								'target': '_blank',
2030								'href': infolink,
2031								'title': "More information"
2032							}, "Info"));
2033						}
2034						details.addEventListener("toggle", this._onDetailsToggle);
2035
2036						parent.appendChild(details);
2037
2038					}
2039				}
2040			},
2041
2042			_onDetailsToggle: function(e) {
2043				//console.info('BotMon.live.gui.lists._onDetailsToggle()');
2044
2045				const target = e.target;
2046
2047				if (target.getAttribute('data-loaded') == 'false') { // only if not loaded yet
2048					target.setAttribute('data-loaded', 'loading');
2049
2050					const fillType = target.getAttribute('data-group');
2051					const fillList = BotMon.live.data.analytics.groups[fillType];
2052					if (fillList && fillList.length > 0) {
2053
2054						const ul = BotMon.t._makeElement('ul');
2055
2056						fillList.forEach( (it) => {
2057							ul.appendChild(BotMon.live.gui.lists._makeVisitorItem(it, fillType));
2058						});
2059
2060						target.appendChild(ul);
2061						target.setAttribute('data-loaded', 'true');
2062					} else {
2063						target.setAttribute('data-loaded', 'false');
2064					}
2065
2066				}
2067			},
2068
2069			_makeVisitorItem: function(data, type) {
2070
2071				// shortcut for neater code:
2072				const make = BotMon.t._makeElement;
2073
2074				let ipType = ( data.ip.indexOf(':') >= 0 ? '6' : '4' );
2075				if (data.ip == '127.0.0.1' || data.ip == '::1' ) ipType = '0';
2076
2077				const platformName = (data._platform ? data._platform.n : 'Unknown');
2078				const clientName = (data._client ? data._client.n: 'Unknown');
2079
2080				const sumClass = ( !data._seenBy || data._seenBy.indexOf(BM_LOGTYPE.SERVER) < 0 ? 'noServer' : 'hasServer');
2081
2082				const li = make('li'); // root list item
2083				const details = make('details');
2084				const summary = make('summary', {
2085					'class': sumClass
2086				});
2087				details.appendChild(summary);
2088
2089				const span1 = make('span'); /* left-hand group */
2090
2091				if (data._type !== BM_USERTYPE.KNOWN_BOT) { /* No platform/client for bots */
2092					span1.appendChild(make('span', { /* Platform */
2093						'class': 'icon_only platform pf_' + (data._platform ? data._platform.id : 'unknown'),
2094						'title': "Platform: " + platformName
2095					}, platformName));
2096
2097					span1.appendChild(make('span', { /* Client */
2098						'class': 'icon_only client client cl_' + (data._client ? data._client.id : 'unknown'),
2099						'title': "Client: " + clientName
2100					}, clientName));
2101				}
2102
2103				// identifier:
2104				if (data._type == BM_USERTYPE.KNOWN_BOT) { /* Bot only */
2105
2106					const botName = ( data._bot && data._bot.n ? data._bot.n : "Unknown");
2107					span1.appendChild(make('span', { /* Bot */
2108						'class': 'has_icon bot bot_' + (data._bot ? data._bot.id : 'unknown'),
2109						'title': "Bot: " + botName
2110					}, botName));
2111
2112				} else if (data._type == BM_USERTYPE.KNOWN_USER) { /* User only */
2113
2114					span1.appendChild(make('span', { /* User */
2115						'class': 'has_icon user_known',
2116						'title': "User: " + data.usr
2117					}, data.usr));
2118
2119				} else { /* others */
2120
2121
2122					/*span1.appendChild(make('span', { // IP-Address
2123						'class': 'has_icon ipaddr ip' + ipType,
2124						'title': "IP-Address: " + data.ip
2125					}, data.ip));*/
2126
2127					span1.appendChild(make('span', { /* Internal ID */
2128						'class': 'has_icon session typ_' + data.typ,
2129						'title': "ID: " + data.id
2130					}, data.id));
2131				}
2132
2133				// country flag:
2134				if (data.geo && data.geo !== 'ZZ') {
2135					span1.appendChild(make('span', {
2136						'class': 'icon_only country ctry_' + data.geo.toLowerCase(),
2137						'data-ctry': data.geo,
2138						'title': "Country: " + ( data._country || "Unknown")
2139					}, ( data._country || "Unknown") ));
2140				}
2141
2142				// referer icons:
2143				if ((data._type == BM_USERTYPE.PROBABLY_HUMAN || data._type == BM_USERTYPE.LIKELY_BOT) && data.ref) {
2144					const refInfo = BotMon.live.data.analytics.getRefererInfo(data.ref);
2145					span1.appendChild(make('span', {
2146						'class': 'icon_only referer ref_' + refInfo.id,
2147						'title': "Referer: " + data.ref
2148					}, refInfo.n));
2149				}
2150
2151				summary.appendChild(span1);
2152				const span2 = make('span'); /* right-hand group */
2153
2154					span2.appendChild(make('span', { /* first-seen */
2155						'class': 'has_iconfirst-seen',
2156						'title': "First seen: " + data._firstSeen.toLocaleString() + " UTC"
2157					}, BotMon.t._formatTime(data._firstSeen)));
2158
2159					span2.appendChild(make('span', { /* page views */
2160						'class': 'has_icon pageviews',
2161						'title': data._pageViews.length + " page view(s)"
2162					}, data._pageViews.length));
2163
2164				summary.appendChild(span2);
2165
2166				// add details expandable section:
2167				details.appendChild(BotMon.live.gui.lists._makeVisitorDetails(data, type));
2168
2169				li.appendChild(details);
2170				return li;
2171			},
2172
2173			_makeVisitorDetails: function(data, type) {
2174
2175				// shortcut for neater code:
2176				const make = BotMon.t._makeElement;
2177
2178				let ipType = ( data.ip.indexOf(':') >= 0 ? '6' : '4' );
2179				if (data.ip == '127.0.0.1' || data.ip == '::1' ) ipType = '0';
2180				const platformName = (data._platform ? data._platform.n : 'Unknown');
2181				const clientName = (data._client ? data._client.n: 'Unknown');
2182
2183				const dl = make('dl', {'class': 'visitor_details'});
2184
2185				if (data._type == BM_USERTYPE.KNOWN_BOT) {
2186
2187					dl.appendChild(make('dt', {}, "Bot name:")); /* bot info */
2188					dl.appendChild(make('dd', {'class': 'icon_only bot bot_' + (data._bot ? data._bot.id : 'unknown')},
2189						(data._bot ? data._bot.n : 'Unknown')));
2190
2191					if (data._bot && data._bot.url) {
2192						dl.appendChild(make('dt', {}, "Bot info:")); /* bot info */
2193						const botInfoDd = dl.appendChild(make('dd'));
2194						botInfoDd.appendChild(make('a', {
2195							'href': data._bot.url,
2196							'target': '_blank'
2197						}, data._bot.url)); /* bot info link*/
2198
2199					}
2200
2201				} else { /* not for bots */
2202
2203					dl.appendChild(make('dt', {}, "Client:")); /* client */
2204					dl.appendChild(make('dd', {'class': 'has_icon client cl_' + (data._client ? data._client.id : 'unknown')},
2205						clientName + ( data._client.v > 0 ? ' (' + data._client.v + ')' : '' ) ));
2206
2207					dl.appendChild(make('dt', {}, "Platform:")); /* platform */
2208					dl.appendChild(make('dd', {'class': 'has_icon platform pf_' + (data._platform ? data._platform.id : 'unknown')},
2209						platformName + ( data._platform.v > 0 ? ' (' + data._platform.v + ')' : '' ) ));
2210
2211					/*dl.appendChild(make('dt', {}, "ID:"));
2212					dl.appendChild(make('dd', {'class': 'has_icon ip' + data.typ}, data.id));*/
2213				}
2214
2215				dl.appendChild(make('dt', {}, "IP-Address:"));
2216				const ipItem = make('dd', {'class': 'has_icon ipaddr ip' + ipType});
2217					ipItem.appendChild(make('span', {'class': 'address'} , data.ip));
2218					ipItem.appendChild(make('a', {
2219						'class': 'icon_only extlink ipinfo',
2220						'href': `https://ipinfo.io/${encodeURIComponent(data.ip)}`,
2221						'target': 'ipinfo',
2222						'title': "View this address on IPInfo.io"
2223					} , "DNS Info"));
2224					ipItem.appendChild(make('a', {
2225						'class': 'icon_only extlink abuseipdb',
2226						'href': `https://www.abuseipdb.com/check/${encodeURIComponent(data.ip)}`,
2227						'target': 'abuseipdb',
2228						'title': "Check this address on AbuseIPDB.com"
2229					} , "Check on AbuseIPDB"));
2230				dl.appendChild(ipItem);
2231
2232				if (Math.abs(data._lastSeen - data._firstSeen) < 100) {
2233					dl.appendChild(make('dt', {}, "Seen:"));
2234					dl.appendChild(make('dd', {'class': 'seen'}, data._firstSeen.toLocaleString()));
2235				} else {
2236					dl.appendChild(make('dt', {}, "First seen:"));
2237					dl.appendChild(make('dd', {'class': 'firstSeen'}, data._firstSeen.toLocaleString()));
2238					dl.appendChild(make('dt', {}, "Last seen:"));
2239					dl.appendChild(make('dd', {'class': 'lastSeen'}, data._lastSeen.toLocaleString()));
2240				}
2241
2242				dl.appendChild(make('dt', {}, "User-Agent:"));
2243				dl.appendChild(make('dd', {'class': 'agent'}, data.agent));
2244
2245				dl.appendChild(make('dt', {}, "Languages:"));
2246				dl.appendChild(make('dd', {'class': 'langs'}, ` [${data.accept}]`));
2247
2248				if (data.geo && data.geo !=='') {
2249					dl.appendChild(make('dt', {}, "Location:"));
2250					dl.appendChild(make('dd', {
2251						'class': 'has_icon country ctry_' + data.geo.toLowerCase(),
2252						'data-ctry': data.geo,
2253						'title': "Country: " + data._country
2254					}, data._country + ' (' + data.geo + ')'));
2255				}
2256
2257				dl.appendChild(make('dt', {}, "Session ID:"));
2258				dl.appendChild(make('dd', {'class': 'has_icon session typ_' + data.typ}, data.id));
2259
2260				dl.appendChild(make('dt', {}, "Seen by:"));
2261				dl.appendChild(make('dd', undefined, data._seenBy.join(', ') ));
2262
2263				dl.appendChild(make('dt', {}, "Visited pages:"));
2264				const pagesDd = make('dd', {'class': 'pages'});
2265				const pageList = make('ul');
2266
2267				/* list all page views */
2268				data._pageViews.sort( (a, b) => a._firstSeen - b._firstSeen );
2269				data._pageViews.forEach( (page) => {
2270					pageList.appendChild(BotMon.live.gui.lists._makePageViewItem(page));
2271				});
2272				pagesDd.appendChild(pageList);
2273				dl.appendChild(pagesDd);
2274
2275				/* bot evaluation rating */
2276				if (data._type !== BM_USERTYPE.KNOWN_BOT && data._type !== BM_USERTYPE.KNOWN_USER) {
2277					dl.appendChild(make('dt', undefined, "Bot rating:"));
2278					dl.appendChild(make('dd', {'class': 'bot-rating'}, ( data._botVal ? data._botVal : '–' ) + ' (of ' + BotMon.live.data.rules._threshold + ')'));
2279
2280					/* add bot evaluation details: */
2281					if (data._eval) {
2282						dl.appendChild(make('dt', {}, "Bot evaluation:"));
2283						const evalDd = make('dd');
2284						const testList = make('ul',{
2285							'class': 'eval'
2286						});
2287						data._eval.forEach( test => {
2288
2289							const tObj = BotMon.live.data.rules.getRuleInfo(test);
2290							let tDesc = tObj ? tObj.desc : test;
2291
2292							// special case for Bot IP range test:
2293							if (tObj.func == 'fromKnownBotIP') {
2294								const rangeInfo = BotMon.live.data.ipRanges.match(data.ip);
2295								if (rangeInfo) {
2296									const owner = BotMon.live.data.ipRanges.getOwner(rangeInfo);
2297									tDesc += ' (range: “' + rangeInfo.cidr + '”, ' + owner + ')';
2298								}
2299							}
2300
2301							// create the entry field
2302							const tstLi = make('li');
2303							tstLi.appendChild(make('span', {
2304								'data-testid': test
2305							}, tDesc));
2306							tstLi.appendChild(make('span', {}, ( tObj ? tObj.bot : '—') ));
2307							testList.appendChild(tstLi);
2308						});
2309
2310						// add total row
2311						const tst2Li = make('li', {
2312							'class': 'total'
2313						});
2314						/*tst2Li.appendChild(make('span', {}, "Total:"));
2315						tst2Li.appendChild(make('span', {}, data._botVal));
2316						testList.appendChild(tst2Li);*/
2317
2318						evalDd.appendChild(testList);
2319						dl.appendChild(evalDd);
2320					}
2321				}
2322				// return the element to add to the UI:
2323				return dl;
2324			},
2325
2326			// make a page view item:
2327			_makePageViewItem: function(page) {
2328				//console.log("makePageViewItem:",page);
2329
2330				// shortcut for neater code:
2331				const make = BotMon.t._makeElement;
2332
2333				// the actual list item:
2334				const pgLi = make('li');
2335
2336				const row1 = make('div', {'class': 'row'});
2337
2338					row1.appendChild(make('a', { // page id is the left group
2339						'href': DOKU_BASE + 'doku.php?id=' + encodeURIComponent(page.pg),
2340						'target': 'preview',
2341						'hreflang': page.lang,
2342						'title': "PageID: " + page.pg
2343					}, page.pg)); /* DW Page ID */
2344
2345					// get the time difference:
2346					row1.appendChild(make('span', {
2347						'class': 'first-seen',
2348						'title': "First visited: " + page._firstSeen.toLocaleString() + " UTC"
2349					}, BotMon.t._formatTime(page._firstSeen)));
2350
2351				pgLi.appendChild(row1);
2352
2353				/* LINE 2 */
2354
2355				const row2 = make('div', {'class': 'row'});
2356
2357					// page referrer:
2358					if (page._ref) {
2359						row2.appendChild(make('span', {
2360							'class': 'referer',
2361							'title': "Referrer: " + page._ref.href
2362						}, page._ref.hostname));
2363					} else {
2364						row2.appendChild(make('span', {
2365							'class': 'referer'
2366						}, "No referer"));
2367					}
2368
2369					// visit duration:
2370					let visitTimeStr = "Bounce";
2371					const visitDuration = page._lastSeen.getTime() - page._firstSeen.getTime();
2372					if (visitDuration > 0) {
2373						visitTimeStr = Math.floor(visitDuration / 1000) + "s";
2374					}
2375					const tDiff = BotMon.t._formatTimeDiff(page._firstSeen, page._lastSeen);
2376					if (tDiff) {
2377						row2.appendChild(make('span', {'class': 'visit-length', 'title': 'Last seen: ' + page._lastSeen.toLocaleString()}, tDiff));
2378					} else {
2379						row2.appendChild(make('span', {
2380							'class': 'bounce',
2381							'title': "Visitor bounced"}, "Bounce"));
2382					}
2383
2384				pgLi.appendChild(row2);
2385
2386				return pgLi;
2387			}
2388		}
2389	}
2390};
2391
2392/* launch only if the BotMon admin panel is open: */
2393if (document.getElementById('botmon__admin')) {
2394	BotMon.init();
2395}