User:Seav/common.js
Jump to navigation
Jump to search
Note: After publishing, you may have to bypass your browser's cache to see the changes.
- Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
- Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
- Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
- Opera: Press Ctrl-F5.
/*jshint esversion: 6 */
// Allows to rearrange statements per property. Useful for arranging things like population chronologically.
mw.loader.load('//www.wikidata.org/w/index.php?title=User:Tohaomg/rearrange_values.js&action=raw&ctype=text/javascript');
// Loads cityQids, muniQids, and cityMuniQids corresponding to a list of QIDs for the PH cities and municipalities
mw.loader.load('//www.wikidata.org/w/index.php?title=User:Seav/const-lgus.js&action=raw&ctype=text/javascript');
const MAX_COOKBOOK_ATTEMPTS = 20;
const COOKBOOK_ATTEMPT_INTERVAL = 500; // in ms
var cookbookButtonText = 'Remove P708';
var cookbookUrlTrigger = 'removeP708';
var cookbookQids = []; //cityMuniQids;
var cookbookStep;
var currentSelector;
var numCookbookAttempts;
var cookbookVars = {};
var cookbook = [
{
isInverted: true,
selector: '#P708',
step: function() {
goToNextItem();
return false;
},
continueIfSelectionFailed: true,
},
{
selector: '#P708 .wikibase-toolbar-button-edit a',
step: function() {
$(currentSelector)[0].click();
return true;
},
},
{
selector: [
'#P708 textarea',
'#P708 .wikibase-toolbar-button-remove a',
],
step: function() {
$(currentSelector[1]).trigger('click');
return true;
},
},
{
isInverted: true,
selector: '#P708',
step: function() {
$(currentSelector).trigger('click');
return true;
},
},
];
function doCookbook() {
cookbookStep = 0;
numCookbookAttempts = 0;
attemptCookbookStep();
}
function attemptCookbookStep() {
var cookbookStepInfo = cookbook[cookbookStep];
var isInverted = cookbookStepInfo.isInverted;
currentSelector = cookbookStepInfo.selector;
if (
checkSelector(currentSelector) && !isInverted ||
!checkSelector(currentSelector) && isInverted
) {
if (cookbookStepInfo.step()) goToNextStep();
return;
}
else if (cookbookStepInfo.continueIfSelectionFailed) {
goToNextStep();
return;
}
numCookbookAttempts++;
if (numCookbookAttempts > MAX_COOKBOOK_ATTEMPTS) {
console.log('Selection unsuccessful');
return;
}
setTimeout(attemptCookbookStep, COOKBOOK_ATTEMPT_INTERVAL);
}
function goToNextStep() {
if (cookbookStep + 1 < cookbook.length) {
cookbookStep++;
numCookbookAttempts = 0;
setTimeout(attemptCookbookStep, COOKBOOK_ATTEMPT_INTERVAL);
}
else {
goToNextItem();
}
}
function checkSelector(selector) {
if (Array.isArray(selector)) {
var isPresent = true;
selector.forEach(function(item) { if (!$(item)[0]) isPresent = false; });
return isPresent;
}
else {
return $(selector)[0] ? true : false;
}
}
function goToNextItem() {
var currentQid = window.location.pathname.substr(6);
for (var i = 0; i < cookbookQids.length; i++) {
if (cookbookQids[i] === currentQid && i + 1 < cookbookQids.length) {
window.location = '/wiki/' + cookbookQids[i + 1] + '?' + cookbookUrlTrigger;
return;
}
}
}
(function(mw, $) {
function init() {
if (window.location.search === '?' + cookbookUrlTrigger) {
doCookbook();
}
else if ($('#P988')[0]) {
var div = document.createElement('div');
div.innerHTML = cookbookButtonText;
div.style.position = 'fixed';
div.style.top = '10px';
div.style.left = '10px';
div.style.background = '#236';
div.style.color = '#fff';
div.style.padding = '10px';
div.style.borderRadius = '5px';
div.style.cursor = 'pointer';
document.body.appendChild(div);
div.addEventListener('click', doCookbook);
}
// Add menu items for barangay items
if ($('#P31 [href="/wiki/Q61878"]').length >= 1) {
$('#p-tb .vector-menu-content-list').append('<li><a href="javascript:setBarangayAliases()">🤖 Set barangay aliases</a></li>');
$('#p-tb .vector-menu-content-list').append('<li><a href="javascript:setBarangayDescriptions()">🤖 Set barangay descriptions</a></li>');
}
}
$(function() { mw.hook('wikipage.content').add(init); });
} (mediaWiki, jQuery));
//importScript('User:Vvekbv/recoin.js');
var CsrfToken;
var CsrfTokenPromise;
function fetchCsrfToken() {
if (!CsrfTokenPromise) {
CsrfTokenPromise = fetch('/w/api.php?action=query&meta=tokens&format=json')
.then(function(response) { return response.json(); })
.then(function(json) {
CsrfToken = json.query.tokens.csrftoken;
return CsrfToken;
});
}
return CsrfTokenPromise;
}
function getCurrentQid() {
return location.pathname.split('/').reverse()[0];
}
// Returns a promise
function fetchEntityJson(qid) {
if (!qid) qid = getCurrentQid();
return (
fetch('/entity/' + qid + '.json')
.then(function(response) { return response.json(); })
.then(function(json) { return json.entities[qid]; })
);
}
// Returns simple value or QID
// TODO: parse more value types
function getPropertyMostPreferredValue(entity, pid) {
var vals = entity.claims[pid].filter(function(val) { return val.rank === 'preferred'; });
if (vals.length === 0) vals = entity.claims[pid].filter(function(val) { return val.rank === 'normal'; });
const mainSnak = vals[0].mainsnak;
if (mainSnak.datatype === 'wikibase-item')
return mainSnak.datavalue.value.id;
else if (mainSnak.datatype === 'quantity')
return parseFloat(mainSnak.datavalue.value.amount);
}
var CurrentBarangay; // Promise
const CurrentBarangayInfo = {
barangay: null,
cityMuni: null,
parentIsCity: null,
cityIsHuc: null,
province: null,
};
// Sets the basic EN, TL, CEB, ES descriptions for the current barangay
function setBarangayDescriptions() {
var info;
Promise.all([fetchBarangayAndParentEntities(), fetchCsrfToken()]).then(function(values) {
info = values[0];
var parentEnLabel = getLabel(info.cityMuni.labels, 'en');
var parentEnLabelHasCity = parentEnLabel.match(/ City$/);
return sendDescription(info.barangay.title, 'en', (
'barangay of the Philippines in ' +
(info.parentIsCity ? (parentEnLabelHasCity ? '' : 'the city of ') : 'the municipality of ') +
parentEnLabel +
(info.cityIsHuc ? '' : ', ' + getLabel(info.province.labels, 'en'))
));
})
.then(function() {
console.log('EN description was set!');
$('.wikibase-entitytermsforlanguageview-en .wikibase-entitytermsforlanguageview-description').css('background', '#cef');
var parentEnLabel = getLabel(info.cityMuni.labels, 'tl');
var parentEnLabelHasCity = parentEnLabel.match(/^Lungsod/);
return sendDescription(info.barangay.title, 'tl', (
'barangay ng Pilipinas sa ' +
(info.parentIsCity ? (parentEnLabelHasCity ? '' : 'lungsod ng ') : 'bayan ng ') +
parentEnLabel +
(info.cityIsHuc ? '' : ', ' + getLabel(info.province.labels, 'tl'))
));
})
.then(function() {
console.log('TL description was set!');
$('.wikibase-entitytermsforlanguageview-tl .wikibase-entitytermsforlanguageview-description').css('background', '#cef');
var parentEnLabel = getLabel(info.cityMuni.labels, 'ceb');
var parentEnLabelHasCity = parentEnLabel.match(/^Dakbayan/);
return sendDescription(info.barangay.title, 'ceb', (
'barangay sa Pilipinas sa ' +
(info.parentIsCity ? (parentEnLabelHasCity ? '' : 'dakbayan sa ') : 'lungsod sa ') +
parentEnLabel +
(info.cityIsHuc ? '' : ', ' + getLabel(info.province.labels, 'ceb'))
));
})
.then(function() {
console.log('CEB description was set!');
$('.wikibase-entitytermsforlanguageview-ceb .wikibase-entitytermsforlanguageview-description').css('background', '#cef');
var parentEnLabel = getLabel(info.cityMuni.labels, 'es');
var parentEnLabelHasCity = parentEnLabel.match(/Ciudad/);
return sendDescription(info.barangay.title, 'es', (
'barangay de Filipinas en ' +
(info.parentIsCity ? (parentEnLabelHasCity ? 'la ' : 'la ciudad de ') : 'el municipio de ') +
parentEnLabel +
(info.cityIsHuc ? '' : ', ' + getLabel(info.province.labels, 'es'))
));
})
.then(function() {
console.log('ES description was set!');
$('.wikibase-entitytermsforlanguageview-es .wikibase-entitytermsforlanguageview-description').css('background', '#cef');
});
}
// Sets the basic EN, TL, CEB aliases for the current barangay
function setBarangayAliases() {
var info;
const aliases = {};
Promise.all([fetchBarangayAndParentEntities(), fetchCsrfToken()]).then(function(values) {
info = values[0];
var enLabel = getLabel(info.barangay.labels, 'en' );
var tlLabel = getLabel(info.barangay.labels, 'tl' );
var cebLabel = getLabel(info.barangay.labels, 'ceb');
var nameHasBarangay = getLabel(info.barangay.labels, 'en').match(/^Barangay/);
aliases.en = [
nameHasBarangay ? null : 'Barangay ' + enLabel,
'Brgy. ' + (nameHasBarangay ? enLabel.replace(/^Barangay /, '') : enLabel),
'Bgy. ' + (nameHasBarangay ? enLabel.replace(/^Barangay /, '') : enLabel),
enLabel + ', ' + getLabel(info.cityMuni.labels, 'en'),
].filter(function(i) { return i });
aliases.tl = [
nameHasBarangay ? null : 'Barangay ' + tlLabel,
'Brgy. ' + (nameHasBarangay ? tlLabel.replace(/^Barangay /, '') : tlLabel),
'Bgy. ' + (nameHasBarangay ? tlLabel.replace(/^Barangay /, '') : tlLabel),
tlLabel + ', ' + getLabel(info.cityMuni.labels, 'tl'),
].filter(function(i) { return i });
aliases.ceb = [
nameHasBarangay ? null : 'Barangay ' + cebLabel,
'Brgy. ' + (nameHasBarangay ? cebLabel.replace(/^Barangg?ay /, '') : cebLabel),
'Bgy. ' + (nameHasBarangay ? cebLabel.replace(/^Barangg?ay /, '') : cebLabel),
cebLabel + ', ' + getLabel(info.cityMuni.labels, 'ceb'),
].filter(function(i) { return i });
if (info.parentIsCity && !getLabel(info.cityMuni.labels, 'en').match(/ City$/)) {
aliases.en.push(aliases.en[3] + ' City');
}
if (!info.cityIsHuc) {
aliases.en .push(aliases.en [aliases.en .length-1] + ', ' + getLabel(info.province.labels, 'en' ));
aliases.tl .push(aliases.tl [aliases.tl .length-1] + ', ' + getLabel(info.province.labels, 'tl' ));
aliases.ceb.push(aliases.ceb[aliases.ceb.length-1] + ', ' + getLabel(info.province.labels, 'ceb'));
}
console.log(aliases);
return sendAliases(info.barangay.title, 'en', aliases.en);
})
.then(function() {
console.log('EN aliases were set!');
$('.wikibase-entitytermsforlanguageview-en .wikibase-entitytermsforlanguageview-aliases').css('background', '#cef');
return sendAliases(info.barangay.title, 'tl', aliases.tl);
})
.then(function() {
console.log('TL aliases were set!');
$('.wikibase-entitytermsforlanguageview-tl .wikibase-entitytermsforlanguageview-aliases').css('background', '#cef');
return sendAliases(info.barangay.title, 'ceb', aliases.ceb);
})
.then(function() {
console.log('CEB aliases were set!');
$('.wikibase-entitytermsforlanguageview-ceb .wikibase-entitytermsforlanguageview-aliases').css('background', '#cef');
});
}
function sendDescription(qid, langCode, description) {
const url = '/w/api.php?action=wbsetdescription' +
'&id=' + qid +
'&language=' + langCode +
'&value=' + encodeURIComponent(description);
return fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'token=' + encodeURIComponent(CsrfToken),
});
}
function sendAliases(qid, langCode, aliases) {
const url = '/w/api.php?action=wbsetaliases' +
'&id=' + qid +
'&language=' + langCode +
'&set=' + encodeURIComponent(aliases.join('|'));
return fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'token=' + encodeURIComponent(CsrfToken),
});
}
function fetchBarangayAndParentEntities() {
if (!CurrentBarangay) {
CurrentBarangay = fetchEntityJson()
.then(function(entity) {
CurrentBarangayInfo.barangay = entity;
const parentQid = getPropertyMostPreferredValue(entity, 'P131');
return fetchEntityJson(parentQid);
})
.then(function(entity) {
CurrentBarangayInfo.cityMuni = entity;
const instanceOf = getPropertyMostPreferredValue(entity, 'P31');
CurrentBarangayInfo.parentIsCity = (instanceOf === 'Q29946056' || instanceOf === 'Q106079704' || instanceOf === 'Q106078286');
const isHuc = instanceOf === 'Q29946056';
CurrentBarangayInfo.cityIsHuc = isHuc;
if (isHuc) {
return null;
}
else {
const parentQid = getPropertyMostPreferredValue(entity, 'P131');
return fetchEntityJson(parentQid);
}
})
.then(function(entity) {
if (entity !== null) CurrentBarangayInfo.province = entity;
return CurrentBarangayInfo;
});
}
return CurrentBarangay;
}
// With fallback to English
function getLabel(labels, langCode) {
return (langCode in labels ? labels[langCode] : labels.en).value;
}