User:Frlgin/moreIdentifiers nukat fix.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.
/**
 * Based on a brilliant idea of user Epìdosis
 */
importStylesheet( 'User:Bargioni/moreIdentifiers.css' );

if( typeof(moreIdentifiers_props)=="undefined" ) {
    importScript( 'User:Bargioni/moreIdentifiers_defaultconf.js' );
}

importScript( 'User:Bargioni/moreIdentifiers_system_regex.js' );

 	
(function(){ // let's define a scope for this script

var wgUserLanguage = mw.config.get( 'wgUserLanguage' );

var select_all_viaf_sources = "SELECT ?id ?idLabel ?cod ?regex ?url_formatter \
WHERE { \
  ?id wdt:P31 wd:Q55586529 . \
  ?id wdt:P1793 ?regex . \
  ?id wdt:P1630 ?url_formatter . \
  ?id p:P1552 [ ps:P1552 wd:Q26921380; pq:P3295 ?cod ] . \
  SERVICE wikibase:label { bd:serviceParam wikibase:language \""+wgUserLanguage+",en\". } \
}";

var viaf_sources;

/**
 * Get property from URI
 */
function get_property_from_uri(uri) {
	var uri_parts = uri.split(/\//);
	return uri_parts[uri_parts.length-1];
}

/**
 * Escape html chars
 */
function escapeHtml(text) {
    'use strict';
    return text.replace(/[\"&<>]/g, function (a) {
        return { '"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;' }[a];
    });
}

/**
 * Gather VIAF sources from Wikidata's descriptions
 */
function save_viaf_sources(J) {
	// J is a json response from the Wikidata's sparql
	var O = {}; // new Object;
	var sources = J.results.bindings;
	for (var i=0; i < sources.length; i++) {
		var source = sources[i];
		var uri = source.id.value;
		var property = get_property_from_uri(uri);
		O[property] = {}; // new Object;
		O[property].code = source.cod.value;
		O[property].label = source.idLabel.value;
		O[property].regex = source.regex.value;
		O[property].url_formatter = source.url_formatter.value;
	}
	return O;
}

/**
 * From code used in VIAF to property P of the ID used in Wikidata
 */
function get_property_from_code (C) {
	for (var viaf_source in viaf_sources) {
		if (viaf_sources[viaf_source].code == C) {
			return viaf_source;
		}
	}
	return '';
}

/**
 * Filter out unwanted VIAF sources
 */
function useful (cluster_sources, cluster_source, sources) {
	if (cluster_source == 'WKP') return false; // always reject Wikidata
	if ( $.inArray(cluster_source, moreIdentifiers_props.unwanted_cluster_sources) >= 0 ) return false; // reject others, if any
	if ( get_property_from_code(cluster_source) ) return true;
	return false;
}
/**
 * Verify that an id matches the regex as in the corresponding P1793
 */
function verify_regex (id, cluster_source) {
	var P = get_property_from_code(cluster_source);
	var re = new RegExp ('^' + viaf_sources[P].regex + '$');
	if (re.test(id)) return id; // id matches the regex of P
	return '';
}

/**
 * Adapt an ID used in VIAF to the form used in Wikidata
 */
function adapt (id, cluster_source) {
	if (!moreIdentifiers_regexps[cluster_source]) return id;
	var regexp, repl;
	if (Array.isArray(moreIdentifiers_regexps[cluster_source])) {
		for (var q = 0; q < moreIdentifiers_regexps[cluster_source].length; q++) {
			regexp = moreIdentifiers_regexps[cluster_source][q].regexp;
			repl = moreIdentifiers_regexps[cluster_source][q].repl;
			id = id.replace(regexp, repl);
		}		
		return id;
	}
	else {
		regexp = moreIdentifiers_regexps[cluster_source].regexp;
		repl = moreIdentifiers_regexps[cluster_source].repl;
		return id.replace(regexp, repl);
	}
}

/**
 * Show identifiers from VIAF
 */
function show_ids (cluster_sources, cluster_source, sources) {
	var P = get_property_from_code(cluster_source);
	for (var i=0; i < cluster_sources[cluster_source].length; i++) {
		var id = cluster_sources[cluster_source][i];
		var id2 = adapt(id, cluster_source);
		id2 = verify_regex(id2, cluster_source);
		if(!id2){
			if(cluster_source==="BNF") {
				id2 = 'cb' + id.replace("http://catalogue.bnf.fr/ark:/12148/",'').replace ( /\D/g , '' ).substring(0,8); // Digits only
				var bnf_xdigits = '0123456789bcdfghjkmnpqrstvwxz'; // A few lines from https://en.wikisource.org/wiki/User:Inductiveload/BnF_ARK_format
				var bnf_check_digit = 0;
				for (i=0; i < id2.length; i++){
					bnf_check_digit += bnf_xdigits.indexOf(id2[i]) * (i+1);
				}
				id2 = "http://catalogue.bnf.fr/ark:/12148/" + id2 + bnf_xdigits[bnf_check_digit % bnf_xdigits.length]; //29 is the radix
				id2 = adapt(id2, cluster_source);
				id2 = verify_regex(id2, cluster_source);
			}
		}
		var id3 = ''; if (!id2) id3 = '<span class="line-through" title="unfit ID">' + id + '</span>';
		if (!sources[P]) {
			var L = escapeHtml(viaf_sources[P].label);
			var checkbox = '<input class="moreIdentifiers_checkbox" \
				type="checkbox" name="'+cluster_source+'" \
				data-raw="'+id+'" data-id="'+id2+'" \
				data-property="'+get_property_from_code(cluster_source)+'" \
				data-cluster-id="'+cluster_sources.viafID+'"/> ';
			var span1 = '<span title="'+L+'">';
			var span2 = '</span>';
			if (id2) {
				// add link to id2
				let url_formatter = viaf_sources[P].url_formatter;
				let id2_href = url_formatter.replace(/\$1/,id2);
				id2 = '<a href="'+id2_href+'" target="_blank">' + id2 + '</a>';
			}
			$('#viaf_cluster_'+cluster_sources.viafID)
				.append('<div class="moreIdentifiers_missing_id">'+ checkbox + span1 + cluster_source + span2
				+ ': ' + (id2 || id3)
				+ '</div>');
			if (id3) $('#viaf_cluster_'+cluster_sources.viafID).find('input:last').prop('disabled',true);
		}
	}
}

/**
 * Show useful identifiers found in a cluster
 */
function show_source (cluster_sources, cluster_source, sources) {
	if (useful(cluster_sources, cluster_source, sources))
		show_ids(cluster_sources, cluster_source, sources);
}

/**
 * Given @nsid, return #text from sources
 */
function from_source_id_to_text_id ( source_id, full_cluster ) {
	var fcss = full_cluster.sources.source;
	if (!Array.isArray(fcss)) 
		fcss = [fcss]; // fcss force array
	for (var p=0; p < fcss.length; p++) {
		if (fcss[p]['@nsid'] == source_id) return fcss[p]['#text'];
	}
	return source_id; // '' sarebbe meglio?
}

/**
 * Get heading from cluster
 */
function get_heading_from_cluster (source, source_id, full_cluster) {
	source_id = from_source_id_to_text_id ( source_id, full_cluster );
	if (!Array.isArray(full_cluster.mainHeadings.data)) 
		// full_cluster.mainHeadings.data force array
		full_cluster.mainHeadings.data = [full_cluster.mainHeadings.data];
	for (var n=0; n < full_cluster.mainHeadings.data.length; n++) {
		var fcmh = full_cluster.mainHeadings.data[n];
		if (!Array.isArray(fcmh.sources.sid)) fcmh.sources.sid = [fcmh.sources.sid]; // fcmh.sources.sid force array
		// if ($.inArray(source+'|'+source_id,fcmh.sources.sid) > -1) {
		if ($.inArray(source_id,fcmh.sources.sid) > -1) {
			return escapeHtml(fcmh.text);
		}
	}
	return '?'; // ???
}

/**
 * Append heading to checkbox
 */
function add_heading (div,full_cluster) {
	var source = $(div).find('span').text();
	var source_id = $(div).find('input').attr('data-raw');
	var heading = get_heading_from_cluster(source,source_id,full_cluster);
	$(div).append(' <div class="moreIdentifiers_heading">'+heading+'</div>');
	// button to report invalid entry in cluster
	var Q = mw.config.get( 'wbEntityId' );
	var viaf = $(div).find('input').attr('data-cluster-id');
	var p = $(div).find('input').attr('data-property');
	var code = $(div).find('input').attr('name');
	var id = $(div).find('input').attr('data-raw');
	var F1 = '\u26a1'; // lightning, fulmine
	var F2 = `/w/index.php?title=Wikidata:VIAF/cluster/conflating_specific_entries&action=edit&section=new&preloadtitle=\{\{Q|${Q}\}\}&preload=Wikidata:VIAF/cluster/conflating%20specific%20entries/preload&preloadparams[]=${viaf}&preloadparams[]=${p}&preloadparams[]=${code}&preloadparams[]=${id}`;
	var F3 = '<a target="_blank" href="'+F2+'">'+F1+'</a>';
	$(div).append(' <span class="moreIdentifiers_lightning" title="report error in VIAF">'+F3+'</span>'); // test
	if(code==='NUKAT'){
		input=div.querySelector('input[data-raw]')
		nukat_vtls=input.getAttribute('data-raw')
		nukat_src=full_cluster.sources.source.reverse().find(s=>s['@nsid']===nukat_vtls)
		nukat_persistent_id =nukat_src['#text'].split('|')[1]
		// wikidata normalizes (only) ids starting with n - https://www.wikidata.org/wiki/Property:P1207#P3202
		if(nukat_persistent_id.startsWith('n')) nukat_persistent_id = nukat_persistent_id.replace(/ +/,'');
		input.setAttribute('data-raw',nukat_persistent_id)
		input.setAttribute('data-id',nukat_persistent_id)
		input.removeAttribute('disabled')
		
		span=div.querySelector('span.line-through')
		span.innerHTML="<a href='https://wikidata-externalid-url.toolforge.org/?p=1207&url_prefix=http://nukat.edu.pl/aut/&id="+nukat_persistent_id+"'>" + nukat_persistent_id + "</a>"
		span.classList.remove('line-through')
		span.setAttribute('title','')
	}
	if(div.firstChild.name==='FAST'){
		input=div.querySelector('input[data-raw]')
		fast_long=input.getAttribute('data-raw')
		fast_short=fast_long.match(/\d+/)[0]
		fast_short=fast_short.replace(/^0+/,'') //replace leading zeroes
		input.setAttribute('data-raw',fast_short)
		input.setAttribute('data-id',fast_short)
		input.removeAttribute('disabled')
		
		span=div.querySelector('span.line-through')
		span.innerText=fast_short
		span.classList.remove('line-through')
		span.setAttribute('title','')
	}
}

/**
 * Add headings
 */
function add_headings (viafid) {
	// console.log('add_headings for cluster '+viafid); // test
	var url = 'https://viaf.org/viaf/' + viafid + '/viaf.json';
	$.getJSON(url,function(full_cluster){
		var divs = $('.moreIdentifiers_missing_id');
		for (var m=0; m < divs.length; m++) {
			var div = divs[m];
			var v = $(div).find('input').attr('data-cluster-id');
			if (v == full_cluster.viafID) add_heading(div, full_cluster);
		}
	});
}

/**
 * Retrieve links from VIAF cluster and show IDs not yet listed in the item
 */
function get_show_ids_from_cluster (viafid, sources) {
	var url = 'https://viaf.org/viaf/' + viafid + '/justlinks.json';
	$.getJSON(url,function(cluster_sources){
		for (var cluster_source in cluster_sources) {
			show_source(cluster_sources, cluster_source, sources);
		}
		// click on cluster checkbox toggles source checkboxes
		$('#viaf_cluster_'+cluster_sources.viafID+'>input').on('click',function(){
			var flag = $(this).is(":checked");
			$('#viaf_cluster_'+cluster_sources.viafID+'>div>input').not(':disabled').prop('checked',flag);
		});
		if ($('#viaf_cluster_'+cluster_sources.viafID).find('.moreIdentifiers_missing_id').length === 0) {
			$('#viaf_cluster_'+cluster_sources.viafID)
				.append('<div class="moreIdentifiers_no_ids">no missing identifiers from this cluster</div>');
			// checkbox is unuseful, disable it?
			// $('#viaf_cluster_'+cluster_sources.viafID+'>input').prop('disabled',true);
		}
		else {
			add_headings (cluster_sources.viafID);
		}
	})
	.fail(function(){$('#viaf_cluster_'+viafid).append(' Warning: Unable to load links')});
}

/**
 * Add close button (x) and ⓘ
 */
function add_close_button () {
	$('#moreIdentifiers_fieldset').prepend(
		'<div style="text-align:right"> \
		<span id="moreIdentifiers_info" title="about this gadget"><a href="/wiki/User:Bargioni/moreIdentifiers" target="_blank">&#9432;</a></span> \
		<span id="moreIdentifiers_close" title="remove this gadget from the page">×</span> \
		</div>'
		);
	$('#moreIdentifiers_close').css({'cursor':'pointer', 'position':'relative', 'top':'-10px'});
	$('#moreIdentifiers_info').css({'cursor':'pointer', 'position':'relative', 'top':'-10px'});
	$('#moreIdentifiers_close').on('click',function(){
		var target = $('#moreIdentifiers_fieldset');
		target.hide('slow', function(){ target.remove(); });
	})	
}

/**
 * Add the interface which allows to quickly add claims with missing IDs
 */
// function moreIdentifiers_addinterface(qid, prop, viaf_sources) {
function moreIdentifiers_addinterface(qid, viaf_sources) {
	// works with instances listed in moreIdentifiers_props.accepted_P31
	var instance_id = moreIdentifiers_checktype(qid, moreIdentifiers_props.accepted_P31);
	if (instance_id === 0) return;

	// look at identifiers in the item
	if ($('#identifiers').length === 0) return; // no identifiers, nothing to do

	// we have section identifiers
	var ids = $('.wikibase-statementgrouplistview>div').get(2); // the block containing identifiers
	var div_ids = $(ids).find('>div'); // the divs of each identifier; inside each div, more identifiers can exist: .find('a.external')
	div_ids = div_ids.toArray();
	
	if (
		div_ids.length === 0 ||
		typeof moreIdentifiers_props === "undefined" || 
		typeof moreIdentifiers_regexps === "undefined"
	) {
		// section identifiers not yet loaded, wait and try again
		mw.moreIdentifiers_retries++;
		if (mw.moreIdentifiers_retries >= mw.moreIdentifiers_max_retries) {
			console.error('moreIdentifiers: end of tries, something was not loaded!');
			return; // stop trying
		}
		setTimeout(function(){
			moreIdentifiers_addinterface(qid, viaf_sources);
		}, 200);
		return;
	}
	
	var sources = {}; // new Object;
	for (var i = 0; i < div_ids.length; i++) {
		var source = $(div_ids[i]);
		var property = source.attr('id');
		sources[property] = []; //new Array;
		var as = source.find('a.external:visible'); // one or more
		as = as.toArray();
		for (var j=0; j < as.length; j++) {
			var a = $(as[j]);
			sources[property].push(a.text());
		}
	}
	
	if (sources.P214) {
    	var $fieldset = $('<fieldset id="moreIdentifiers_fieldset"><legend>Add More Identifiers from VIAF</legend></fieldset>')
		.insertAfter($('.wikibase-statementgrouplistview').first());
		add_close_button();
		$fieldset.append('<table id="moreIdentifiers_table"><tr><td id="moreIdentifiers"></td><td id="moreIdentifiers_command"></td></tr></table>');
		var button = '<div><button id="moreIdentifiers_button_add" class="moreIdentifiers_button">Add checked identifiers</button> <span id="moreIdentifiers_gear"></span></div>';
		$('#moreIdentifiers_command').append(button);
		$('.moreIdentifiers_button').on('click',function(){
			$('#moreIdentifiers_reload_button').remove();
			$(".moreIdentifiers_added_msg").remove();
			mw.claim_id = 0;
			$('#moreIdentifiers_fieldset').prop('disabled',true); // disable the fieldset
			$('#moreIdentifiers_button_add').css('opacity','0.4'); // dim button Add
//			$('#moreIdentifiers_button_add').prop('disabled', true); // disable button Add
//			$('.viaf_cluster>input[type=checkbox]').prop('disabled',true); // disable cluster checkboxes
//			$('.moreIdentifiers_checkbox').prop('disabled',true) // disable any checkbox
			add_ids_sequentially2();
		});
		var results = '<div id="moreIdentifiers_results"></div>';
		$('#moreIdentifiers_command').append(results);
		
		var checkbox = '<input type="checkbox"/>';
		var ranks = $('#P214 .ui-icon-rankselector');
		for (var k=0; k < sources.P214.length; k++) {
			var deprecated_cluster = '';
			if ($(ranks[k]).hasClass('wikibase-rankselector-deprecated')) { // deprecated VIAF cluster
				deprecated_cluster = '<span class="deprecated_cluster">Warning: deprecated cluster</span>';
			}
			var viafid = sources.P214[k];
			$('#moreIdentifiers').append('<div class="viaf_cluster" id="viaf_cluster_'+viafid+'">'+checkbox+' <b>VIAF cluster '+viafid+'</b> '+deprecated_cluster+'</div>');
			get_show_ids_from_cluster(viafid,sources);
		}
	}
}

/**
 * Add a formatted claim and in case of success show succtext
 */
function moreIdentifiers_addclaim(claim, succtext) {
    var api = new mw.Api();
    var token = mw.user.tokens.values.csrfToken;
    api.post({ 
		action: 'wbsetclaim',
		summary: "via [[Q106876944]]",
		claim: JSON.stringify(claim),
		token: token
	}).then(
		function(aw){
			if(aw.success == 1) {
				$('#moreIdentifiers_results').append( succtext );
				// console.log('ok',aw); // test
				add_ids_sequentially2();
			}
			else { // never used?
				$('#moreIdentifiers_results').append( '<div class="moreIdentifiers_error_msg">save failed</div>' );
				console.log('ko',aw);
			}
		})
		.catch(function(aw) {
			console.log('ko',aw);
			$('#moreIdentifiers_results').append( '<div class="moreIdentifiers_error_msg">save failed!</div>' );
			add_ids_sequentially2();
		}) 
}

/**
 * Add a reference to a claim that states info was retrieved from VIAF now
 */
function moreIdentifiers_addreference (claim, viaf_cluster) {
	var now = '+'+(new Date()).toISOString().substr(0,10)+'T00:00:00Z'; // WD doesn't handle hhmmss
	var references = [
		{
			"snaks-order": ["P248", "P214", "P813"],
			"snaks": {
				"P248": [
					{
						"snaktype": "value",
						"property": "P248", // source of info
						"datavalue": {
							"value": {
								"entity-type": "item",
								"numeric-id": "54919"  // VIAF Q54919
							},
							"type": "wikibase-entityid"
						}
					}
				],
				"P214": [
					{
						"snaktype": "value",
						"property": "P214", // VIAF ID
						"datavalue": {
							"value": viaf_cluster,
							"type": "string"
						},
						"datatype": "external-id"
					}
				],
				"P813": [
					{
						"snaktype": "value",
						"property": "P813", // stated on
						"datatype": "time",
						"datavalue": {
							"value": {
								"after": 0,
								"before": 0,
								"calendarmodel": "http://www.wikidata.org/entity/Q1985727",
								"precision": 11,
								"time": now,
								"timezone": 0
							},
							"type": "time"
						}
					}
				]
			}
		}
	];
	claim.references = references;
	return claim;	
}
 
/**
 * Add a statement with datatype 'string'
 * qid: the qid of the item wich should get the statement
 * pid: the property to add
 * pname: the name of the property for showing a success-note
 * str: the value of the statement
 */
function moreIdentifiers_addstringstatement(qid, pid, pname, str, viaf_cluster) {
    var claim = {
		id: (new wb.utilities.ClaimGuidGenerator("q" + qid)).newGuid(),
		type: "claim",
		mainsnak: {
			snaktype: "value",
			property: "P" + pid,
			datatype: "external-id", // "string",
			datavalue: {
				value: str,
				type: "string"
			}
		}
	};
	claim = moreIdentifiers_addreference(claim, viaf_cluster);
	// console.log( claim ); // test
	moreIdentifiers_addclaim(claim,  "<div class=\"moreIdentifiers_added_msg\">Added "+pname+" \""+str+"\"</div>");
}

/**
 * Add claims to the item, async FAILS! UNUSED
 */
function add_ids () {
	for (var i=0; i < $('.moreIdentifiers_checkbox:checked').length; i++) {
		var cb = $('.moreIdentifiers_checkbox:checked')[i];
		var qid = mw.config.get( 'wbEntityId' ).substring(1);
		var pname = $(cb).attr('name');
		var pid = get_property_from_code(pname).substring(1);
		var str = $(cb).attr('data-id');
		var viaf_cluster = $(cb).attr('data-cluster-id');
		// console.log(new Date(), 'Lancio', qid, pid, pname, str, viaf_cluster);
		moreIdentifiers_addstringstatement(qid, pid, pname, str, viaf_cluster);
	}
}

/**
 * Autoreload the page after adding missing identifiers
 */
function autoreload () {
	if (moreIdentifiers_props.autoreload) {
		if (moreIdentifiers_props.autoreload_timeout) {
			$('#moreIdentifiers_results')
				.append('<div>This page will be automatically reloaded in '+moreIdentifiers_props.autoreload_timeout+' ms.</div>');
			setTimeout(function(){location.reload()},moreIdentifiers_props.autoreload_timeout)
		}
		else {
			location.reload(); // param true or false? TODO
		}
	}
	else {
		// add button to reload the page
		$('#moreIdentifiers_results').append(
			'<div><button id="moreIdentifiers_reload_button" class="moreIdentifiers_button" title="reload this page to see changes">Reload this page</button></div>'
		);
		$('#moreIdentifiers_results').find('button').on('click',function(){location.reload()}); // param true or false? TODO
	}
}

/**
 * Add claims to the item in sequence, version 2
 */
function add_ids_sequentially2 () {
	// console.log(new Date().valueOf(), 'chiamata', mw.claim_id); // test
	if (mw.claim_id >= $('.moreIdentifiers_checkbox:checked').length) { // end of claims
		$('#moreIdentifiers_gear').text('');
		$('#moreIdentifiers_button_add').prop('disabled', false); // enable button Add
		$('#moreIdentifiers_button_add').css('opacity','1'); // restore opacity of button Add
		$('#moreIdentifiers_fieldset').prop('disabled',false); // enable the fieldset
//		$('.moreIdentifiers_checkbox').not(':checked').prop('disabled',false); // enable unchecked checkboxes
//		$('.moreIdentifiers_checkbox:checked').prop('checked',false); // stop use of saved checkboxes
//		$('.viaf_cluster input[type=checkbox]').prop('disabled',false); // enable cluster checkboxes
		if ($('.moreIdentifiers_checkbox:checked').length) autoreload();
		return false;
	}
	var cb = $('.moreIdentifiers_checkbox:checked')[mw.claim_id];
	var qid = mw.config.get( 'wbEntityId' ).substring(1);
	var pname = $(cb).attr('name');
	var pid = get_property_from_code(pname).substring(1);
	var str = $(cb).attr('data-id');
	var viaf_cluster = $(cb).attr('data-cluster-id');
	// console.log(new Date().valueOf(), 'lancio', qid, pid, pname, str, viaf_cluster);
	$('#moreIdentifiers_gear').text((mw.claim_id+1) + ' of '+ $('.moreIdentifiers_checkbox:checked').length);
	moreIdentifiers_addstringstatement(qid, pid, pname, str, viaf_cluster);
	mw.claim_id++;
}

/**
 * Add claims to the item in sequence UNUSED
 */
function add_ids_sequentially () {
	// console.log('chiamata', mw.claim_id, moreIdentifiers_promises); // test
	if (mw.claim_id >= $('.moreIdentifiers_checkbox:checked').length) return; // end of claims
	if (mw.claim_id > moreIdentifiers_promises) {
		setTimeout(function(){
			// console.log('attesa',mw.claim_id,moreIdentifiers_promises); // test
			add_ids_sequentially();
		},500); // wait
	}
	var cb = $('.moreIdentifiers_checkbox:checked')[mw.claim_id];
	var qid = mw.config.get( 'wbEntityId' ).substring(1);
	var pname = $(cb).attr('name');
	var pid = get_property_from_code(pname).substring(1);
	var str = $(cb).attr('data-id');
	var viaf_cluster = $(cb).attr('data-cluster-id');
	// console.log(new Date(), 'Lancio', qid, pid, pname, str, viaf_cluster);
	moreIdentifiers_addstringstatement(qid, pid, pname, str, viaf_cluster);
	mw.claim_id++;
	add_ids_sequentially(); // next claim
}

/**
 * check if the item has instance in accepted instances
 */
function moreIdentifiers_checktype(qid, prop_list) {
	var instances = $('#P31').find(".wikibase-snakview-value a").toArray();
	if (instances.length > 0 && moreIdentifiers_props.accepted_P31.includes('any')) return 1; // allow any instance - aded 2021-04-22
	for (i=0; i < instances.length;i++) {
		var instance = instances[i];
		if (typeof instance.attributes.href === "undefined") return false;
		var instance_id = $(instance).attr('href').replace(/\/wiki\/Q/,'');
		var instance_pos = $.inArray(instance_id, prop_list);
		if (instance_pos !== -1) return prop_list[instance_pos];
	}
	return 0;
}

$( function($) {

    /**
     * Check if we're viewing an item
     */
    var qid = mw.config.get( 'wbEntityId' );
    if ( !qid ) {
		return;
    }
    else {
		qid = qid.substring(1);
    }

	// works with instances listed in moreIdentifiers_props.accepted_P31
//	var instance_id = moreIdentifiers_checktype(qid, moreIdentifiers_props.accepted_P31);
//	if (instance_id === 0) return;
	
	mw.moreIdentifiers_retries = 0;
	mw.moreIdentifiers_max_retries = 50;
	mw.claim_id;

	/**
	 * Get properties of all VIAF sources 
	 */
	const endpointUrl = 'https://query.wikidata.org/sparql',
		sparqlQuery = select_all_viaf_sources,
		fullUrl = endpointUrl + '?query=' + encodeURIComponent( sparqlQuery ),
		headers = { 'Accept': 'application/sparql-results+json' };
	fetch( fullUrl, { headers } ).then( body => body.json() ).then( json_response => {
		viaf_sources = save_viaf_sources(json_response);
		// moreIdentifiers_addinterface(qid, instance_id, viaf_sources);
		moreIdentifiers_addinterface(qid, viaf_sources);
	} );

} );

})(); // end of scope