Gebruiker:MakiBoy/Gadget-LogCounter.js

Uit Wikikids
Naar navigatie springen Naar zoeken springen

Let op! Nadat je de veranderingen hebt opgeslagen, moet je de cache van je browser nog legen om ze daadwerkelijk te zien.

Mozilla (incl. Firefox) ctrl-shift-r
IE ctrl-f5
Opera f5
Safari cmd-r
Konqueror f5
/* jshint sub:true maxerr:100000 */
// [[User:MakiBoy/Gadget-LogCounter.js]] gemaakt door [[User:MakiBoy]], onderhouden door [[User:Rots61]]

var version = '3.0';
var searchBarLC;
function parseNumber(number) {
    return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}

function addZero(number) {
	return number < 10 ? "0" + number : number;
}

function showProjectLogCounter(pages) {
	console.log(pages);
    document.getElementsByTagName("h1")[0].textContent = "Speciaal:Statistieken WikiKids";
    document.title = "Statistieken WikiKids";

    searchBarLC = '<div><input type="text" id="lc-searchbar"> <button onclick="searchContainsLogCounter();">Bevat</button><button onclick="searchExactLogCounter();">Pagina</button></div>'
        + '<button onclick="reloadPagesLogCounter();">Laad alles opnieuw in</button>';
    var logCounterInfo = '<div id="logCounterInfo">Deze pagina laat zien hoeveel paginabezoeken er zijn geweest op een specifieke pagina. De rij "Views" bevat <b>alle</b> views. De rij daarachter laat alleen maar zien hoeveel views komen vanuit iets specifieks, bijvoorbeeld vanuit een categorie of van een mobiele telefoon. <a href="/Speciaal:Statistieken_WikiKids?action=tabel">Klik hier voor statistieken van vorige weken.</a> </div>';
    if (mw.config.get('wgTitle') === "LogCounter") {
    	logCounterInfo += '<span style="color:red;">Gebruik voortaan "Speciaal:Statistieken WikiKids"</span><br>'; 
    }
    var table = document.createElement('table');
    table.classList.add('wikitable');
    var tableHead = document.createElement('thead');
    var tableHeadRow = document.createElement('tr');
    var tableHeadTitles;
    if (infoHistory) {
    	tableHeadTitles = ['Paginatitel', 'Laatste bezoek', 'Views', infoHistory.Types, '%'];
    } else {
    	tableHeadTitles = ['Paginatitel', 'Laatste bezoek', 'Views', 'Links', '%'];
    }
    var tableBody = document.createElement('tbody');

    var currentPage = 1;
    var rowsPerPage = parameterLC['rows'] ? parseInt(parameterLC['rows']) : 25;
    var totalPages = Math.ceil(pages.length / rowsPerPage);

    function showPage(pageNumber) {
        currentPage = pageNumber;
        tableBody.innerHTML = '';
        var start = (currentPage - 1) * rowsPerPage;
        var end = start + rowsPerPage;
        var paginatedItems = pages.slice(start, end);
        paginatedItems.forEach(function (page) {
            var row = document.createElement('tr');
            var totalVisitors, mainPageVisited, pageTitle, pageLink, date;
            if (historyLogCounter) {
            	if (!page.nV) { // bij een gedeelte van de opgeslagen data, wordt nV of mPV leeggelaten, dit zorgt ervoor dat het juist wordt weergegeven. Dit is alleen nodig bij een voorgaande versie. Bij huidige versies worden alles gewoon doorgegeven. 
            		totalVisitors = page.mPV;
            	} else if (!page.mPV) {
            		totalVisitors = page.nV;
            	} else {
		            totalVisitors = page.nV + page.mPV;
            	}
	            mainPageVisited = page.mPV ? page.mPV : "";
	            pageTitle = page.t.replace(/_/g, ' ');
	            pageLink = page.t;
	            date = new Date(page.uA);
            } else {
	            totalVisitors = page.normalVisitors + page.mainPageVisitors;
	            mainPageVisited = page.mainPageVisitors ? page.mainPageVisitors : "";
	            pageTitle = page.title.replace(/_/g, ' ');
	            pageLink = page.title;
	            date = new Date(page.updatedAt);
            }
            var percentMainPage = Math.round((100/totalVisitors)*mainPageVisited*100)/100;
            var percentStyle = '>';
            if (percentMainPage < parameterLC['percentmax']) { // 60 < 70 true 
            	if (percentMainPage > parameterLC['percentmin'] || parameterLC['percentmin'] === null) { // 60 > 50 true
            		percentStyle = ' style="background:lightgreen"><span style="font-size:0px">Voldoet aan vereisten QQQ</span>';
            	} 
            } else if (percentMainPage > parameterLC['percentmin']) { 
            	if (!parameterLC['percentmax']) {
            		percentStyle = ' style="background:lightgreen"><span style="font-size:0px">Voldoet aan vereisten QQQ</span>';
            	}
            }
            var dateString; 
            if (!isNaN(date)) {
            	dateString = addZero(date.getDate()) + "-" + addZero((date.getMonth() + 1)) + "-" + date.getFullYear() + " " + addZero(date.getHours()) + ":" + addZero(date.getMinutes());
            } else {
            	dateString = "Niet beschikbaar";
            }
			if (parameterLC['only'] && percentStyle === '>') {
			} else {
	            row.innerHTML = `<td><a href="/${pageLink}">${pageTitle}</a></td>
	                <td>${dateString}</td>
	                <td>${parseNumber(totalVisitors)}</td><td>${parseNumber(mainPageVisited)}</td>
	                <td ${percentStyle + percentMainPage}</td>`;
	            tableBody.appendChild(row);
			}
        });
    }

    showPage(1);

    var pagination = document.createElement('div');
    pagination.classList.add('pagination');

    var prevButton = document.createElement('button');
    prevButton.textContent = 'Vorige';
    prevButton.style = 'margin-right: 10px;';
    prevButton.addEventListener('click', function () {
		if (currentPage > 1) {
            showPage(currentPage - 1);
            //Manier waarop je kunt zien op welke pagina je bent
            document.getElementById('pageCounter').innerHTML = `Pagina <input id="logcounternumberpage" type="number" size="5" value=${currentPage}> van ${totalPages}`;
        }
    });
    pagination.appendChild(prevButton);

    var pageCounter = document.createElement('span');
    pageCounter.id = "pageCounter";
    pageCounter.innerHTML = `Pagina <input id="logcounternumberpage" type="number" size="5" value=${currentPage}> van ${totalPages}`;
    pagination.appendChild(pageCounter);

    var nextButton = document.createElement('button');
    nextButton.textContent = 'Volgende';
    nextButton.style = 'margin-left: 10px;';
    nextButton.addEventListener('click', function () {
        if (currentPage < totalPages) {
            showPage(currentPage + 1);
            //Manier waarop je kunt zien op welke pagina je bent
            document.getElementById('pageCounter').innerHTML = `Pagina <input id="logcounternumberpage" type="number" size="5" value=${currentPage}> van ${totalPages}`;
        }
    });
    
    var gotoButton = document.createElement('button');
    gotoButton.textContent = 'Gaan';
    gotoButton.style = 'margin-left: 10px;';
    gotoButton.addEventListener('click', function () {
    	if (document.getElementById('logcounternumberpage').value > totalPages || document.getElementById('logcounternumberpage').value < 1) {
    	} else {
			showPage(parseInt(document.getElementById('logcounternumberpage').value));
			document.getElementById('pageCounter').innerHTML = `Pagina <input id="logcounternumberpage" type="number" size="5" value=${currentPage}> van ${totalPages}`;
    	}
    });
    
    pagination.appendChild(gotoButton);
    pagination.appendChild(nextButton);
    
    tableHeadTitles.forEach(function (title) {
        var tableHeadCell = document.createElement('th');
        tableHeadCell.textContent = title;
        tableHeadRow.appendChild(tableHeadCell);
    });
    tableHead.appendChild(tableHeadRow);
    table.appendChild(tableHead);
    table.appendChild(tableBody);

    var totalVisitors = pages.reduce(function (total, page) {
    	if (historyLogCounter) {
    		if (!page.nV) { 
            	return total + page.mPV;
            } else if (!page.mPV) {
            	return total + page.nV;
            } else {
    			return total + page.nV + page.mPV;
            }
    	} else {
    		return total + page.normalVisitors + page.mainPageVisitors;
    	}
    }, 0);

    var totalElement = document.createElement('div');
    totalElement.style = 'margin-top: 20px; display: flex; flex-direction: column;';

    var totalVisitorsElement = document.createElement('span');
    totalVisitorsElement.textContent = `Totaal aantal bezoeken: ${parseNumber(totalVisitors)}`;
    totalElement.appendChild(totalVisitorsElement);

    var totalPagesElement = document.createElement('span');
    totalPagesElement.textContent = `Totaal aantal pagina's: ${parseNumber(pages.length)}`;
    totalElement.appendChild(totalPagesElement);
    
	if (infoHistory) {
		var moreInfoElement = document.createElement('span');
		var xStarttime = new Date(infoHistory.Starttime); 
		var xEndtime = new Date(infoHistory.Endtime); 
		var firstDateString = addZero(xStarttime.getDate()) + "-" + addZero((xStarttime.getMonth() + 1)) + "-" + xStarttime.getFullYear() + " " + addZero(xStarttime.getHours()) + ":" + addZero(xStarttime.getMinutes());
		var lastDateString = addZero(xEndtime.getDate()) + "-" + addZero((xEndtime.getMonth() + 1)) + "-" + xEndtime.getFullYear() + " " + addZero(xEndtime.getHours()) + ":" + addZero(xEndtime.getMinutes());
		moreInfoElement.textContent = `${firstDateString} tot ${lastDateString}`;
	    totalElement.appendChild(moreInfoElement);
	}
    document.getElementById('bodyContent').innerHTML = searchBarLC + logCounterInfo;
    document.getElementById('bodyContent').appendChild(table);
    document.getElementById('bodyContent').appendChild(pagination);
    document.getElementById('bodyContent').appendChild(totalElement);
}

function statsPerPageLogCounter() {
	var allHistoryPages;
    var request = new XMLHttpRequest();
    request.open('GET', 'https://wikikids.nl/api.php?action=query&list=allpages&apminsize=100000&apnamespace=2&apprefix=Rots61/Statistieken&aplimit=500&format=json', false);
    request.send(null);
    if (request.status === 200) {
        allHistoryPages = JSON.parse(request.responseText);
    }
    allHistoryPages = allHistoryPages.query.allpages;
    var tableoutputLC = `<table class="wikitable" id="LogCounterPerPage"><thead><tr><th onclick="sortTable('LogCounterPerPage',0)">Artikel</th><th onclick="sortTable('LogCounterPerPage',1)">Datum</th><th onclick="sortTable('LogCounterPerPage',2)">Aantal bezoekers</th></thead><tbody>`;
	requests = new Array(allHistoryPages.length);
		setTimeout(function () {
		for (let i = 0; i < allHistoryPages.length; i++) {
			console.log(i);
		    requests[i] = new XMLHttpRequest();
		    requests[i].open("GET", "https://wikikids.nl/" + allHistoryPages[i]['title'] + '?action=raw');
		    requests[i].onload = function() {
		        var datainfo = JSON.parse(requests[i].responseText);
		        var result;
			    for (var y = 0; y < datainfo.length; y++) {
			    	console.log(datainfo[y]['t'] + ' ' + y);
			        if (datainfo[y]['t'].toLowerCase() === parameterLC['page'].toLowerCase()) {
			            result = datainfo[y]
			            break;
			        }
			    }
				if (result) {
				    var totaalViews;
		           	if (!result.nV) { // bij een gedeelte van de opgeslagen data, wordt nV of mPV leeggelaten, dit zorgt ervoor dat het juist wordt weergegeven. Dit is alleen nodig bij een voorgaande versie. Bij huidige versies worden alles gewoon doorgegeven. 
	            		totaalViews = result.mPV;
	            	} else if (!result.mPV) {
	            		totaalViews = result.nV;
	            	} else {
			            totaalViews = result.nV + result.mPV;
	            	}
				    tableoutputLC += `<tr><td><a href="/${result['t']}">${result['t']}</a></td><td><a href="https://wikikids.nl/Special:Statistieken_WikiKids?date=${allHistoryPages[i]['title'].slice(-8)}">${allHistoryPages[i]['title'].slice(-8)}</a></td><td>${totaalViews}</td></tr>`;
				} else {
					tableoutputLC += `<tr><td></td><td><a href="https://wikikids.nl/Special:Statistieken_WikiKids?date=${allHistoryPages[i]['title'].slice(-8)}">${allHistoryPages[i]['title'].slice(-8)}</a></td><td>0</td></tr>`
				}
		    };
		    requests[i].send();
		}
	    document.getElementsByTagName("h1")[0].textContent = "Speciaal:" + mw.config.get('wgTitle');
	    document.title = "Pagina specifieke statistieken -  WikiKids";
	    infotext = 'Specifieke statistieken voor ' + parameterLC['page'] + '.';
	    setTimeout( function () { 
	    	tableoutputLC += '</tbody></table>';
	    	console.log(infotext + tableoutputLC);
	    	document.getElementById('bodyContent').innerHTML = infotext + tableoutputLC; 
	    	sortTable('LogCounterPerPage',0);
	    }, 5000);
	}, 500);

}

function getPagesLogCounter() {
    var pages = [];
    var request = new XMLHttpRequest();
    request.open('GET', urlLogCounter, false);
    request.send(null);
    if (request.status === 200) {
        pages = JSON.parse(request.responseText);
    }
    // Sorteer de pagina's op het aantal bezoekers (hoog naar laag) (page.normalVisitors + page.mainPageVisitors)
    pages.sort(function (a, b) {
    	if (historyLogCounter) {
    		return b.nV + b.mPV - a.nV - a.mPV;
    	} else {
    		return b.normalVisitors + b.mainPageVisitors - a.normalVisitors - a.mainPageVisitors;
    	}
    });
    return pages;
}

function searchContainsLogCounter(searchQuery) {
    if (!searchQuery) {
        searchQuery = document.getElementById('lc-searchbar').value.replace(/ /g, '_');
    }
    var allPages = getPagesLogCounter();
    var titlecheck = historyLogCounter ? 't': 'title'; 
    var searchResult = [];
    for (var i = 0; i < allPages.length; i++) {
        if (allPages[i][titlecheck].toLowerCase().includes(searchQuery.toLowerCase())) {
            searchResult.push(allPages[i]);
        }
    }
    setTimeout(function () {
        if (!searchResult.length) {
    		var printToScreen = '<br>De pagina <a href="https://wikikids.nl/' + searchQuery + '">' + searchQuery + '</a> heeft geen views ontvangen of bestaat niet.' 
        	+ 'Kijk voor meer <a href="https://wikikids.nl/WikiKids:Statistieken">informatie op deze pagina</a> Klopt er iets niet? Meld het!';
        	document.getElementById('bodyContent').innerHTML = searchBarLC + printToScreen;
        } else {
        	showProjectLogCounter(searchResult);
        }
    }, 750);
}

function searchExactLogCounter(searchQuery) {
    if (!searchQuery) {
        searchQuery = document.getElementById('lc-searchbar').value.replace(/ /g, '_');
    }
    var allPages = getPagesLogCounter();
    var titlecheck = historyLogCounter ? 't': 'title'; 
    var searchResult = [];
    for (var i = 0; i < allPages.length; i++) {
        if (allPages[i][titlecheck].toLowerCase() === searchQuery.toLowerCase()) {
            searchResult.push(allPages[i]);
        }
    }
    setTimeout(function () {
        if (!searchResult.length) {
    		var printToScreen = '<br>Er is geen pagina die <a href="https://wikikids.nl/Speciaal:Zoeken/' + searchQuery + '">' + searchQuery + '</a> bevat, en die in deze periode views heeft ontvangen.' 
        	+ 'Kijk voor meer <a href="https://wikikids.nl/WikiKids:Statistieken">informatie op deze pagina</a> Klopt er iets niet? Meld het!';
        	document.getElementById('bodyContent').innerHTML = searchBarLC + printToScreen;
        	console.log(allPages);
        	console.log(searchQuery);
        } else {
        	showProjectLogCounter(searchResult);
        }
    }, 750);
}


function getInfoPageLogCounter(urlInfoLogCounter) {
    var infoHistory;
    var request = new XMLHttpRequest();
    request.open('GET', urlInfoLogCounter, false);
    request.send(null);
    if (request.status === 200) {
        infoHistory = JSON.parse(request.responseText);
    }
    return infoHistory;
}

function tabelLogCounter() {
	var allHistoryPages;
    var request = new XMLHttpRequest();
    request.open('GET', 'https://wikikids.nl/api.php?action=query&list=allpages&apminsize=100000&apnamespace=2&apprefix=Rots61/Statistieken&aplimit=500&format=json', false);
    request.send(null);
    if (request.status === 200) {
        allHistoryPages = JSON.parse(request.responseText);
    }
    allHistoryPages = allHistoryPages.query.allpages;
    var tableoutputLC = `<table class="wikitable" id="LogCounterHistory"><thead><tr><th onclick="sortTable('LogCounterHistory',0)">Link</th><th onclick="sortTable('LogCounterHistory',1)">Datum</th><th onclick="sortTable('LogCounterHistory',2)">Aantal bezoekers</th><th onclick="sortTable('LogCounterHistory',3)">Aantal pagina's</th><th onclick="sortTable('LogCounterHistory',4)">Extra informatie</th></tr></thead><tbody>
    <tr><td><a href="https://wikikids.nl/Special:Statistieken_WikiKids">Live</a></td><td>Sinds zaterdag</td><td></td><td></td></tr>`;
	requests = new Array(allHistoryPages.length);
		setTimeout(function () {
		for (let i = 0; i < allHistoryPages.length; i++) {
		    var url = "https://wikikids.nl/" + allHistoryPages[i]['title'] + '/info?action=raw';
		    requests[i] = new XMLHttpRequest();
		    requests[i].open("GET", url);
		    requests[i].onload = function() {
		        var datainfo = JSON.parse(requests[i].responseText);
				tableoutputLC += `<tr><td><a href="https://wikikids.nl/Special:Statistieken_WikiKids?date=${allHistoryPages[i]['title'].slice(-8)}">${datainfo['Jaar-Week']}</a></td>`;
				var xStarttime = new Date(datainfo.Starttime); 
				var xEndtime = new Date(datainfo.Endtime); 
				var firstDateString = addZero(xStarttime.getDate()) + "-" + addZero((xStarttime.getMonth() + 1)) + "-" + xStarttime.getFullYear() + " " + addZero(xStarttime.getHours()) + ":" + addZero(xStarttime.getMinutes());
				var lastDateString = addZero(xEndtime.getDate()) + "-" + addZero((xEndtime.getMonth() + 1)) + "-" + xEndtime.getFullYear() + " " + addZero(xEndtime.getHours()) + ":" + addZero(xEndtime.getMinutes());
				tableoutputLC += `<td>van ${firstDateString} tot ${lastDateString}</td><td>${datainfo.Totalviews}</td><td>${datainfo.Totalpages}</td><td><a href="/WikiKids:Statistieken#${datainfo.Types}">${datainfo.Types}</a></td></tr>`;
		    };
		    requests[i].send();
		}
	    document.getElementsByTagName("h1")[0].textContent = "Speciaal:" + mw.config.get('wgTitle');
	    document.title = "Voorgaande statistieken -  WikiKids";
	    infotext = 'Elke zaterdag worden, rond 6 uur, de statistieken opnieuw ingesteld. Een week loopt dus van zaterdag tot zaterdag. Het real-time registreren van de bezoekers wordt mogelijk gemaakt door MakiBoy. Voor vragen kun je terecht bij MakiBoy of Rots61. <br>'
	    + 'Deze lijst wordt automatisch bijgewerkt, zodat alle vorige statistieken worden getoont. <br>';
	    setTimeout( function () { 
	    	tableoutputLC += '</tbody></table>';
	    	document.getElementById('bodyContent').innerHTML = infotext + tableoutputLC; 
	    	sortTable('LogCounterHistory',0);
	    }, 500);
	}, 500);
}

function reloadPagesLogCounter() {
    var allPages = getPagesLogCounter();
    showProjectLogCounter(allPages);
}

function sortTable(id, n) {
  var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
  table = document.getElementById(id);
  switching = true;
  // Set the sorting direction to ascending:
  dir = "asc";
  /* Make a loop that will continue until
  no switching has been done: */
  while (switching) {
    // Start by saying: no switching is done:
    switching = false;
    rows = table.rows;
    /* Loop through all table rows (except the
    first, which contains table headers): */
    for (i = 1; i < (rows.length - 1); i++) {
      // Start by saying there should be no switching:
      shouldSwitch = false;
      /* Get the two elements you want to compare,
      one from current row and one from the next: */
      x = rows[i].getElementsByTagName("TD")[n];
      y = rows[i + 1].getElementsByTagName("TD")[n];
      /* Check if the two rows should switch place,
      based on the direction, asc or desc: */
      if (dir == "asc") {
        if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
          // If so, mark as a switch and break the loop:
          shouldSwitch = true;
          break;
        }
      } else if (dir == "desc") {
        if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
          // If so, mark as a switch and break the loop:
          shouldSwitch = true;
          break;
        }
      }
    }
    if (shouldSwitch) {
      /* If a switch has been marked, make the switch
      and mark that a switch has been done: */
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
      // Each time a switch is done, increase this count by 1:
      switchcount ++;
    } else {
      /* If no switching has been done AND the direction is "asc",
      set the direction to "desc" and run the while loop again. */
      if (switchcount === 0 && dir === "asc") {
        dir = "desc";
        switching = true;
      }
    }
  }
}

if (mw.config.get('wgNamespaceNumber') === -1 && (mw.config.get('wgTitle') === "LogCounter" || (mw.config.get('wgTitle') === "Statistieken Wikikids" ||mw.config.get('wgTitle') === "Statistieken WikiKids"))) {
	var parameterLC = {};
	parameterLC['rows'] = mw.util.getParamValue('rows');
	parameterLC['action'] = mw.util.getParamValue('action');
	parameterLC['date'] = mw.util.getParamValue('date');
	parameterLC['page'] = mw.util.getParamValue('page').replace(/ /g, '_');
	parameterLC['percentmin'] = mw.util.getParamValue('percentmin');
	parameterLC['percentmax'] = mw.util.getParamValue('percentmax');
	parameterLC['only'] = mw.util.getParamValue('only');
	if (parameterLC['percentmin'] === parameterLC['percentmax']) {
		parameterLC['percentmin'] = 100; 
	}
	if (parameterLC['action'] === 'tabel') {
		tabelLogCounter();
	} else if (parameterLC['page']) { 
		statsPerPageLogCounter();
	} else {
		document.getElementById("footer-places").innerHTML += '<li id="footer-places-gadget-LogCounter">Script gemaakt door <a href="/User:MakiBoy" title="Gebruiker:MakiBoy">MakiBoy</a>, versie: ' + version + '</li>';
	    if (parameterLC['date']) {
	    	var urlLogCounter = 'https://wikikids.nl/User:Rots61/Statistieken/' + parameterLC['date'] + '?action=raw';
	    	var historyLogCounter = true;
	    	var infoHistory = getInfoPageLogCounter('https://wikikids.nl/User:Rots61/Statistieken/' + parameterLC['date'] + '/info?action=raw');
	    } else {
	    	var urlLogCounter = 'https://wikikids.martvanweeghel.nl/pages';
	    }
        var allPages = getPagesLogCounter();
        showProjectLogCounter(allPages);
	    }
	}
Afkomstig van Wikikids , de interactieve Nederlandstalige Internet-encyclopedie voor en door kinderen. "https://wikikids.nl/index.php?title=Gebruiker:MakiBoy/Gadget-LogCounter.js&oldid=771269"