User:Goldzahn/test.js
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.
// copied and adapted from:
// [[User:Magnus Manske/wikidata_useful.js]]
// Version 1.00: two boxes; the first box is for occupations, taken from [[User:ValterVB/Sandbox]] (new)
// the second box is for countries.
// some functions from Magnus Manske version are deleted.
// Version 2.07: added stack for storing property and value in two cookies
// Version 3.00: storing two different values; three cookies
// Version 3.22: storing box don´t allow typos
// Version 3.23: more locations foe <instance of>
// Version 3.24: unbundling properties
// Version 3.25: label works
// Version 4.00: user can add p- and q- rows
// Version 5.02: load one select from wikipage User:<your datafile>/data Example: User:Goldzahn/data
// Version 5.03: patch from User:Zuphilip (wrong test if statement is already there)
// Version 5.04: deleted p107 (main type), because p31 (is a) and p279 (subclass of) are used now
var self = this ;
var q = mw.config.get('wgPageName').toLowerCase() ;
self.q = q ;
self.queue = [] ;
id_cnt = 0 ;
api = '/w/api.php' ;
var pq = [];
function processNextQueueItem() {
var self = this ;
if ( self.queue.length === 0 ) {
if ( self.processed === 0 ) {
return ;
}
// DONE
console.log ( "DONE" ) ;
return ;
}
var q = self.queue.shift () ;
if ( undefined === q.entity ) q.entity = self.q ; // wgPageName
if ( q.mode === 'set' ) {
var val = '{"entity-type":"item","numeric-id":' + q.target_entity.replace(/\D/g,'') + '}' ;
self.tryCreateClaim ( q.entity , q.prop , val ) ; // entity ersetzt durch target_entity
} else {
console.log ( q ) ;
}
}
//patched by user Zuphilip
//p,q or P,Q
function tryCreateClaim( entity , property , value ) {
var self = this ;
entity = entity.replace ( /\D/g , '' ) ;
property = property.replace ( /\D/g , '' ) ;
var value2 = JSON.parse ( value ) ;
var nid = value2['numeric-id'] ;
$.getJSON ( self.api , {
action : 'wbgetentities' ,
format : 'json' ,
ids : 'Q'+entity ,
props : 'info|claims'
} , function ( data ) {
console.log(data);
if ( undefined !== data.entities['Q'+entity] ) {
if ( undefined !== data.entities['Q'+entity].claims ) {
if ( undefined !== data.entities['Q'+entity].claims['P'+property] ) {
var n = data.entities['Q'+entity].claims['P'+property] ;
var exists = false ;
$.each ( n , function ( k , v ) {
if ( v.mainsnak.datavalue.value['numeric-id'] == nid ) {
exists = true ;
return false ;
}
} ) ;
if ( exists ) {
console.log ( "P"+property+' exists for Q'+entity ) ;
self.processNextQueueItem() ;
return ;
}
}
}
}
self.createClaim ( 'Q'+entity , 'P'+property , value ) ;
} ) ;
}
//END OF Patch
function createClaim( entity , property , value ) {
// console.log ( "Creating " + entity + " / " + property + " / " + value ) ;
var self = this ;
$.post ( self.api , {
action : 'query' ,
prop : 'info' ,
intoken : 'edit' ,
titles : entity ,
format : 'json'
} , function ( data ) {
var token , lastrevid ;
$.each ( (data.query.pages||[]) , function ( k , v ) {
token = v.edittoken ;
lastrevid = v.lastrevid ;
} ) ;
if ( undefined === token ) {
console.log ( "Cannot get edit token for " + entity ) ;
self.processNextQueueItem() ;
return ;
}
property = property.replace(/\D/g,'') ;
entity = entity.replace(/\D/g,'') ;
var vo = JSON.parse ( value ) ;
var value_id = vo['numeric-id']+'' ;
var other_entity = ( entity.replace(/\D/g,'') != self.q.replace(/\D/g,'') ) ;
$.post ( self.api , {
action : 'wbcreateclaim' ,
entity : 'Q'+entity ,
snaktype : 'value' ,
property : 'P'+property ,
value : value ,
token : token ,
baserevid : lastrevid ,
format : 'json'
} , function ( data ) {
var id = 'added_' + id_cnt ;
var h = "<div id='" + id + "'>" ;
h += "Added " ;
h += "<span class='added_entity_p'>" + property + "</span>" ;
h += " → " ;
h += "<span class='added_entity_q'>" + value_id + "</span>" ;
if ( other_entity ) h += " to entity <span class='added_entity_x'>" + entity + "</span>" ;
h += ".</div>" ;
$($('div.wb-claims').get(0)).append ( h ) ;
self.updateEntity ( id , property , 'P' ) ;
self.updateEntity ( id , value_id , 'Q' ) ;
if ( other_entity ) self.updateEntity ( id , entity.replace(/\D/g,'') , 'x' ) ;
id_cnt++ ;
self.processed++ ;
self.processNextQueueItem() ;
} , 'json' ) ;
} , 'json' ) ;
}
function updateEntity( id , value , prefix ) {
var self = this ;
var q = prefix+value ;
if ( prefix == 'x' ) q = 'Q' + value ;
$.getJSON ( self.api , {
action : 'wbgetentities' ,
ids : q ,
format : 'json'
} , function ( data ) {
var labels = data.entities[q].labels ;
var title = q ;
if ( undefined !== labels ) {
$.each ( ['en','de','fr'] , function ( k , v ) {
if ( undefined === labels[v] ) return ;
title = labels[v].value ;
return false ;
} ) ;
}
var h = "<a href='/wiki/" + q + "'>" + title + "</a>" ;
$('#'+id+' span.added_entity_'+prefix).html ( h ) ;
} ) ;
}
function tryDesc() {
var self = this ;
var lang ;
var title ;
$.each ( ['en','de'] , function ( k , l ) {
var t = $('.wb-sitelinks-link-'+l+' a').text() ;
if ( t === '' ) return ;
lang = l ;
title = t ;
return false ;
} ) ;
if ( lang === undefined ) return ;
$.getJSON ( '//'+lang+'.wikipedia.org/w/api.php?callback=?' , {
action : 'query' ,
prop : 'extracts' ,
exsentences : 5 ,
titles : title ,
format : 'json'
} , function ( data ) {
$.each ( data.query.pages , function ( k , v ) {
$('table.wb-sitelinks').after ( v.extract ) ;
} ) ;
} ) ;
}
function autoName() {
var self = this ;
var key = 'h1 input.wb-ui-propertyedittool-editablevalueinterface' ;
var t = $($(key).get(0)) ;
if ( t.val() !== '' || t.tagName == 'span' ) return ; // Already has a title
$.each ( ['en','de','fr','it','nl','sv'] , function ( k , v ) {
var title = $($('td.wb-sitelinks-link-'+v + ' a').get(0)).text() ;
if ( title === '' ) return ;
title = title.replace ( /\s\(.+$/ , '' ) ;
$($(key).get(0)).val(title).css({'background-color':'red'}) ;
$($(key).get(0)).focus();
return false ;
} ) ;
}
// register ready event
$(document).ready(function () {
if ( mw.config.get('wgNamespaceNumber') !== 0 ) return ;
if ( mw.config.get('wgAction') !== 'view' ) return ;
var text1 = '{"name1": {"property1":"p21","firstlabel":"persons"}, "list1":[{"label":"male","item":"q6581097"}, {"label":"female","item":"q6581072"}]}';
var text2 = '{"name2": {"property2":"p106","firstlabel":"occupations"}, "list2":[{"label":"actor","item":"q33999"},{"label":"archaeologist","item":"q3621491"}, {"label":"architect","item":"q42973"}, {"label":"artist","item":"q483501"}, {"label":"astronaut","item":"q11631"}, {"label":"astronomer","item":"q11063"}, {"label":"aviator","item":"q2095549"}, {"label":"biologist","item":"q864503"}, {"label":"cartoonist","item":"q2489362"}, {"label":"chemist","item":"q593644"}, {"label":"columnist","item":"q1086863"}, {"label":"composer","item":"q36834"}, {"label":"computer scientist","item":"q82594"}, {"label":"designer","item":"q5322166"}, {"label":"economist","item":"q188094"}, {"label":"engineer","item":"q81096"}, {"label":"film producer","item":"q3282637"}, {"label":"film director","item":"q2526255"}, {"label":"football player","item":"q937857"}, {"label":"geologist","item":"q520549"}, {"label":"hacker","item":"q1487"}, {"label":"historian","item":"q201788"}, {"label":"inventor","item":"q205375"}, {"label":"journalist","item":"q1930187"}, {"label":"lawyer","item":"q40348"}, {"label":"mathematician","item":"q170790"}, {"label":"military officer","item":"q189290"}, {"label":"model","item":"q4610556"}, {"label":"musician","item":"q639669"}, {"label":"painter","item":"q1028181"}, {"label":"philosopher","item":"q4964182"}, {"label":"photographer","item":"q33231"}, {"label":"physician","item":"q39631"}, {"label":"physicist","item":"q169470"}, {"label":"pianist","item":"q486748"}, {"label":"politician","item":"q82955"}, {"label":"poet","item":"q49757"}, {"label":"programmer","item":"q5482740"}, {"label":"publisher","item":"q2516866"}, {"label":"scientist","item":"q901"}, {"label":"singer","item":"q177220"}, {"label":"singer-songwriter","item":"q488205"}, {"label":"sportsperson","item":"q2066131"}, {"label":"theologian","item":"q1234713"}, {"label":"writer","item":"q36180"}]}';
// {"label":"","item":""}, {"label":"","item":""}, {"label":"","item":""}, {"label":"","item":""}, {"label":"","item":""}
var obj = JSON.parse(text1);
var obj2 = JSON.parse(text2);
// var obj3 = JSON.parse(text3);
obj.name2 = obj2.name2;
obj.list2 = obj2.list2;
//var h = "<div id='useful_tool' title='useful Tool' class='vectorTabs' style='width: 20px; height: 1.3em; margin-left: 0.5em; margin-right: 0.5em; cursor:pointer'>Tool</div>" ;
//$('#improvedsearch-toggle').after ( h ) ;
var d = "<div id='tool_text' <div style='position:absolute;right:0px;top:15px;z-index:1;background-color:#ffe1bc'> tool V5.04<br/>" ;
d +="<ul style='passing-left:0.5em'>";
d += "<li><select class='frm1'></select></li>" ;
d += "<li><select class='frm2'></select></li>" ;
d += "<li id='id1'><span id='user_data' style='cursor:pointer;background-color:white;padding:1px 5px 1px 5px' title='file: User:your username/data' >load user data</span></li>";
d += "<div id='placeholder'></div>" ;
d +="</ul>";
// d += "<br/><br/>" ;
d += "<table style='border:thin solid black; border-spacing:5px'>";
d += "<tr><td align='center' style='cursor:pointer' id='plus-p' title='add a new row'>p+</td><td align='center'>property</td><td align='center'>label</td></tr>";
d += "<tr id='row-p1'><td><form><input type='checkbox' class='p' id='p1' value='p1' checked='checked' />p1</form></td>";
d += "<td><input type='text' class='property' size='6' maxlength='4' value='p' id='input-p1' /></td>";
d += "<td><input type='text' class='label-p' size='8' maxlength='25' id='label-p1' value='' /></td></tr>";
d += "<tr><td align='center' style='cursor:pointer' id='plus-q' title='add a new row'>q+</td><td align='center'>value</td><td align='center'>label</td></tr>";
d += "<tr id='row-q1'><td><form><input type='checkbox' class='q' id='q1' value='q1' title='transfer to database p and q' />q1</form></td>";
d += "<td><input type='text' class='value' size='6' maxlength='9' value='q' id='input-q1' title='input-q1' /></td>";
d += "<td><input type='text' class='label-q' size='8' maxlength='25' id='label-q1' value='' title='label-q1' /></td></tr>";
d += "<tr><td colspan='4' align='center'><p align='left'>tool says:</p><textarea id='message' cols='18' rows='3'>Clicking p+ and q+ adds new rows. With clicking one p and one q data is transfered to datasource. Loading userdata from file: User:your username/data</textarea></td></tr>";
d += "</table>";
d += "</div></div>" ;
d += "<div id='num-p'></div>" ;
d += "<div id='num-q'></div>" ;
d += "</div>" ;
$('#mw-content-text').append ( d ) ;
var h, i;
h = '' ;
h += "<option>" + obj.name1.firstlabel + "</option>";
for (i = 0, len = obj.list1.length; i < len; i++) {
h += "<option value=obj.list1[i].item>" + obj.list1[i].label + "</option>";
}
$('.frm1').html(h);
h = '' ;
h += "<option>" + obj.name2.firstlabel + "</option>";
for (i = 0, len = obj.list2.length; i < len; i++) {
h += "<option value=obj.list2[i].item>" + obj.list2[i].label + "</option>";
}
$('.frm2').html(h);
pq.p1 = true;
pq.q1 = true;
$('#num-p').val(2); // next p-row
$('#num-q').val(2);
// first block of register events
// register click-event for property
$("#plus-p").on("click", function(event){
var new_span;
var span = [];
span[0] = "<tr id='row-p";
span[1] = "'><td><form><input type='checkbox' class='p' id='p";
span[2] = "'/>p";
span[3] = "</form></td><td><input type='text' class='property' size='6' maxlength='4' id='input-p";
span[4] = "' /></td><td><input type='text' class='label-p' size='8' maxlength='25' id='label-p";
span[5] = "' value='' /></td></tr>";
var n = $('#num-p').val();
new_span = span[0]+n+span[1]+n+span[2]+n+span[3]+n+span[4]+n+span[5];
var p = n - 1 ;
$('#row-p' + p).after(new_span);
$('#num-p').val($('#num-p').val() * 1 + 1);
pq['p' + n] = true; // add new p in array pq
});
// register click-event for value
$("#plus-q").on("click", function(event){
var new_span;
var span = [];
span[0] = "<tr id='row-q";
span[1] = "'><td><form><input id='q";
span[2] = "' type='checkbox' class='q' id='q";
span[3] = "' title='transfer to database p and q' />q";
span[4] = "</form></td><td><input type='text' class='value' size='6' maxlength='9' id='input-q";
span[5] = "' /></td><td><input type='text' class='label-q' size='8' maxlength='25' id='label-q";
span[6] = "' value='' /></td></tr>";
var n = $('#num-q').val();
new_span = span[0]+n+span[1]+n+span[2]+n+span[3]+n+span[4]+n+span[5]+n+span[6];
var q = n - 1 ;
$('#row-q' + q).after(new_span);
$('#num-q').val($('#num-q').val() * 1 + 1);
pq['q' + n] = true; // add new p in array pq
});
// register a blur event for <input-p> or <input-q> tags
// inputs with class = property or value when blur
// $('input.property, input.value').blur(function() {
$('table').on('blur', 'input.property, input.value', function(event){
var search1 = /^[pPqQ][1-9]/ ; // looking for 'p' or 'P' and one number between 1 to 9
var search2 = /\d/ ; // strings following 'p1' or 'q1' which should be a number
var result;
var i = 0;
var a = [];
do {
a[i] = $(this).val().charAt(i);
i = i + 1;
} while (i < $(this).val().length);
result = search1.test(a[0] + a[1]); // console.log(result);
for (i = 2; i < $(this).val().length; i++) {
result = result && search2.test(a[i]); // alert(a[i]);
}
// test if 'p...' or 'q...' is typed into input-p or 'input-q'
var x1 = this.id.charAt(6);
var x2 = $(this).val().toLowerCase().charAt(0);
if (x1 != x2) result = false;
// switching checkboxes on and off depending on 'result'
var new_string = this.id.replace('input', '#elem'); // 'input-p1' > '#elem-p1', 'input-q2' > '#elem-q2'
if (result === true) // {console.log('p is OK')} else {console.log('p is wrong')};
{ $('#message').val(' '); // 'input is valid'
$(this).css('backgroundColor', '#ffffff');
pq[this.id.slice(6, 8)] = true; // 'p1', 'q2', ...
}
else
{ $('#message').val('input is invalid');
$(this).css('backgroundColor', '#F93');
pq[this.id.slice(6, 8)] = false;
};
// console.log('new_string = ' + new_string);
var elem = true;
// gets every element of the pq array
for (var i in pq) {
result = result && pq[i];
}
if (result)
{$('input[type=checkbox]').prop('disabled', false); }
else {$('input[type=checkbox]').prop('disabled', true); };
});
// end first block of register events
var x, y;
x = $.cookie('cookie-p1');
if (x !== null) { // test if there is a cookie
y = x.split('|');
$('#input-p1').val(y[0]);
$('#label-p1').val(y[1]);
$('#input-p1').trigger('blur'); // trigger event. Test if value is valid
var i = 2;
var num =2;
var a, b;
while (i<(y.length-1)) {
$('#plus-p').trigger('click');
a = '#input-p' + num; b = '#label-p' + num; num += 1;
$(a).val(y[i]); i++;
$(b).val(y[i]); i++;
$(a).trigger('blur'); // trigger event. Test if property is valid
}
}
else $('#input-p1').val('p1');
x = $.cookie('cookie-q1');
if (x !== null) { // test if there is a cookie
y = x.split('|');
$('#input-q1').val(y[0]);
$('#label-q1').val(y[1]);
$('#input-q1').trigger('blur'); // trigger event. Test if value is valid
i = 2;
num = 2;
while (i<(y.length-1)) {
$('#plus-q').trigger('click'); // $("td#plus-q").on("click", function(event)
a = '#input-q' + num; b = '#label-q' + num; num += 1;
$(a).val(y[i]); i++;
$(b).val(y[i]); i++;
$(a).trigger('blur'); // trigger event. Test if value is valid
}
}
else $('#input-q1').val('q1');
tryDesc() ;
autoName() ;
// second block of register events
// register toggle Events
//$("#useful_tool").toggle(
// function () {
$("#user_data").on("click", function(event){
$.getJSON ( '//' + 'wikidata.org/w/api.php?callback=?' , {
action : 'parse' ,
// page : 'User:Goldzahn/data' ,
page : 'User:' + mw.config.get('wgUserName') + '/data' ,
format : 'json' ,
prop : 'wikitext'
} , function ( data ) {
if ( undefined === data.parse.wikitext ) {
return ;
}
var text = data.parse.wikitext['*'].replace(/\n/gm,' ') ;
// console.log ('getJSON= ' + text);
var obj_data = JSON.parse(text);
obj.list = obj_data.list;
var h, i;
h = "<div id='userdata'></div>" ;
h += "<li><select class='frm_data'>" ;
h += "<option>user data</option>";
for (i = 0, len = obj.list.length; i < len; i++) {
h += "<option value=obj.list[i].item>" + obj.list[i].label + "</option>";
};
h += "</select></li>" ;
$('#id1').remove () ;
$('#placeholder').html(h);
console.log ('Your datafile should be at: User:'+mw.config.get('wgUserName')+'/data');
$("select.frm_data").change(function () {
var index=this.selectedIndex-1;
if (index >= 0) {
// console.log(obj.list[index].property + " " + obj.list[index].item );
queue.push({mode:'set', prop:obj.list[index].property, target_entity:obj.list[index].item});
self.processNextQueueItem();
}
});
} ) ;
});
$("select.frm1").change(function () {
var index=this.selectedIndex-1;
if (index >= 0) {
// console.log(obj.name1.property1 + " " + obj.list1[index].item);
queue.push({mode:'set', prop:obj.name1.property1, target_entity:obj.list1[index].item});
self.processNextQueueItem();
}
});
$("select.frm2").change(function () {
var index=this.selectedIndex-1;
if (index >= 0) {
// console.log(obj.name2.property2 + " " + obj.list2[index].item );
queue.push({mode:'set', prop:obj.name2.property2, target_entity:obj.list2[index].item});
self.processNextQueueItem();
}
});
// register a blur event for <input-p, label-p> tags
$('table').on('blur', 'input.property, input.label-p', function(event){
// $('input.property, input.label-p').blur(function() {
var n = $('#num-p').val();
var cookie_string = '';
var cookie_elem;
var cookie_label;
for (i=1; i<n; i++) {
cookie_elem = '#input-p' + i;
cookie_label = '#label-p' + i;
if ($(cookie_elem).val() != '') cookie_string += $(cookie_elem).val() + '|' + $(cookie_label).val() + '|';
}
$.cookie('cookie-p1', cookie_string);
});
// register a blur event for <input-q, label-q> tags
// $('input.value, input.label-q').blur(function() {
$('table').on('blur', 'input.value, input.label-q', function(event){
var n = $('#num-q').val();
var cookie_string = '';
var cookie_elem;
var cookie_label;
for (i=1; i<n; i++) {
cookie_elem = '#input-q' + i;
cookie_label = '#label-q' + i;
if ($(cookie_elem).val() != '') cookie_string += $(cookie_elem).val() + '|' + $(cookie_label).val() + '|';
}
$.cookie('cookie-q1', cookie_string);
});
// test that only one p and only one q is checked
$("table").on("click", "input", function(event){
var p_is, q_is;
if ($( "input.p:checked" ).length > 1) $('#message').val('more than one p clicked - please correct input');
if ($( "input.p:checked" ).length == 1) $('#message').val('one p clicked - O.K. ');
if ($( "input.p:checked" ).length == 0) $('#message').val('no p clicked - please correct input');
if ($( "input.p:checked" ).length == 1 && $( "input.q:checked" ).length == 1) {
$('#message').val('one q and one p clicked');
$( "input.p:checked" ).each(function() {
p_is = this.id; // console.log( "p is: " + p_is );
});
$( "input.q:checked" ).each(function() {
q_is = this.id; // console.log( "q is: " + q_is );
})
if (($('#input-' + p_is).val() != '') && ($('#input-' + q_is).val() != '')) {
// {wd_useful.useTransfer(p_is, q_is)
queue.push({mode:'set', prop:$('#input-' + p_is).val(), target_entity:$('#input-' + q_is).val()});
self.processNextQueueItem();
}
else { $('#message').val('empty row clicked - please correct input') };
};
});
});