User:Bargioni/moreIdentifiers.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
 * Update without justlinks.json - 20240525
 */
 
/* jshint multistr: true */
/* jshint esversion: 6 */

mw.loader.using([ 'jquery.ui' ]).then(function () {
console.log('moreIdentifier gadget loading...');
importStylesheet( 'User:Bargioni/moreIdentifiers.css' );
if( typeof(moreIdentifiers_props)=="undefined" ) {
    importScript( 'User:Bargioni/moreIdentifiers_defaultconf.js' );
}
importScript( 'User:Epìdosis/moreIdentifiers_system_regex.js' );

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

/**
 * 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
 */
var select_all_viaf_sources = "SELECT ?id ?cod ?regex ?url_formatter \
WHERE { \
  ?uri wdt:P31 wd:Q55586529; wdt:P1793 ?regex; wdt:P1630 ?url_formatter; \
  p:P1552 [ a wikibase:BestRank; ps:P1552 wd:Q26921380; pq:P3295 ?cod ]. \
  BIND(REPLACE(STR(?uri), 'http://www.wikidata.org/entity/','') AS ?id). \
}";

var viaf_sources;

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 property = source.id.value;
		O[property] = {}; // new Object;
		O[property].code = source.cod.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 (var k=0; k < id2.length; k++) {
					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].code);
			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
				var url_formatter = viaf_sources[P].url_formatter;
				var 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);
		}
		else {
			var N = $('a:contains('+(id2||id)+')').filter(function(i,e){if($(e).text() == (id2||id)) return true; else return false;});
			$(N).parent().append('<span class="mi_in_VIAF" style="margin-left:10px; font-size:0.8em">in VIAF cluster '+cluster_sources.viafID+'</span>');
			$('.wikibase-referenceview').find('span.mi_in_VIAF').remove(); // do not add to references
			$('.moreIdentifiers_missing_id span.mi_in_VIAF').remove(); // do not add to missing IDs
		}
	}
}

/**
 * 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?
}

function adapt_sid_mainHeadings_data(full_cluster) {
	var datas = full_cluster.mainHeadings.data;
	for (var p=0; p < datas.length; p++) {
		var data = datas[p];
		var sources = data.sources;
		var ssid = sources.sid; 
		var sids = ssid;
		if (!Array.isArray(sids)) sids = [sids]; // force array
		for (var r=0; r < sids.length; r++) {
			var [s, id] = sids[r].split(/\|/);
			id = adapt(id, s);
			sids[r] = s+'|'+id; // apply adaptation to cluster
		}
	}
	return full_cluster;
}

/**
 * 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 = [full_cluster.mainHeadings.data];
	full_cluster = adapt_sid_mainHeadings_data(full_cluster);
	for (var n=0; n < full_cluster.mainHeadings.data.length; n++) {
		var fcmh = full_cluster.mainHeadings.data[n]; // force array
		if (!Array.isArray(fcmh.sources.sid))
			fcmh.sources.sid = [fcmh.sources.sid]; // fcmh.sources.sid force array
		if (!Array.isArray(fcmh.sources.s))
			fcmh.sources.s = [fcmh.sources.s]; // fcmh.sources.s force array
		if ($.inArray(source_id,fcmh.sources.sid) > -1) return escapeHtml(fcmh.text);
		if ($.inArray(source+'|'+source_id,fcmh.sources.sid) > -1) return escapeHtml(fcmh.text);
		// if ($.inArray(source_id,fcmh.sources.sid) > -1) return escapeHtml(fcmh.text);
		// if ($.inArray(source,fcmh.sources.s) > -1) return escapeHtml(fcmh.text);
	}
	for (var n=0; n < full_cluster.mainHeadings.data.length; n++) {
		var fcmh = full_cluster.mainHeadings.data[n]; // force array
		if (!Array.isArray(fcmh.sources.sid))
			fcmh.sources.sid = [fcmh.sources.sid]; // fcmh.sources.sid force array
		if (!Array.isArray(fcmh.sources.s))
			fcmh.sources.s = [fcmh.sources.s]; // fcmh.sources.s force array
		// if ($.inArray(source+'|'+source_id,fcmh.sources.sid) > -1) return escapeHtml(fcmh.text);
		if ($.inArray(source_id,fcmh.sources.sid) > -1) return escapeHtml(fcmh.text);
		// if ($.inArray(source,fcmh.sources.s) > -1) return escapeHtml(fcmh.text);
	}
	for (var n=0; n < full_cluster.mainHeadings.data.length; n++) {
		var fcmh = full_cluster.mainHeadings.data[n]; // force array
		if (!Array.isArray(fcmh.sources.sid))
			fcmh.sources.sid = [fcmh.sources.sid]; // fcmh.sources.sid force array
		if (!Array.isArray(fcmh.sources.s))
			fcmh.sources.s = [fcmh.sources.s]; // fcmh.sources.s force array
		// if ($.inArray(source+'|'+source_id,fcmh.sources.sid) > -1) return escapeHtml(fcmh.text);
		// if ($.inArray(source_id,fcmh.sources.sid) > -1) return escapeHtml(fcmh.text);
		if ($.inArray(source,fcmh.sources.s) > -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-id') ? $(div).find('input').attr('data-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
}

/**
 * Add headings
 */
function add_headings (viafid) {
	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_old(viafid, sources) { // unused
	var url = 'https://viaf.org/viaf/' + viafid + '/justlinks.json';			// old justlinks † 23/05/2024
	$.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>');
		}
		else {
			add_headings (cluster_sources.viafID);
		}
	})
	.fail(function(){$('#viaf_cluster_'+viafid).append(' <span style="color:red"> Warning: Unable to load links.</span>');});
}

/**
 * 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, 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

function sort_sources(a,b) {
	return a['#text'].localeCompare(b['#text']);
}

function get_show_ids_from_cluster(viafid, sources) { // 20240524
	var url = 'https://viaf.org/viaf/' + viafid + '/viaf.json';
	var cluster_sources = {}; cluster_sources.viafID = viafid;
	$.getJSON(url,function(cluster){
		if (!Array.isArray(cluster.sources.source))
			cluster.sources.source = [cluster.sources.source]; // cluster.sources.source force array
		cluster.sources.source = cluster.sources.source.sort(sort_sources);
		for (var i=0; i<cluster.sources.source.length; i++) {
			var [s,id] = cluster.sources.source[i]['#text'].split(/\|/);
			if(s == 'DNB' || s == 'LIH' || s == 'SELIBR') id = cluster.sources.source[i]['@nsid'];
			// cluster_sources[s] = [id]; // array of IDs
			!Array.isArray(cluster_sources[s]) ?  cluster_sources[s]=[id] : cluster_sources[s].push(id); // array of IDs
		}
		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(' <span style="color:red"> Warning: Unable to load links. Looks like VIAF has dismissed an API service at the core of this gadget. We will try to patch it ASAP (2024.05.23).</span>');});
}
	// 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: "Added with [[User:Bargioni/moreIdentifiers|moreIdentifiers]]",
		claim: JSON.stringify(claim),
		token: token
	}).then(
		function(aw){
			if(aw.success == 1) {
				$('#moreIdentifiers_results').append( succtext );
				add_ids_sequentially2();
			}
			else { // never used?
				$('#moreIdentifiers_results').append( '<div class="moreIdentifiers_error_msg">save failed</div>' );
			}
		})
		.catch(function(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",
						"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",
			datavalue: {
				value: str,
				type: "string"
			}
		}
	};
	claim = moreIdentifiers_addreference(claim, viaf_cluster);
	moreIdentifiers_addclaim(claim,  "<div class=\"moreIdentifiers_added_msg\">Added "+pname+" \""+str+"\"</div>");
}

/**
 * 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 () {
	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
		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');
	$('#moreIdentifiers_gear').text((mw.claim_id+1) + ' of '+ $('.moreIdentifiers_checkbox:checked').length);
	moreIdentifiers_addstringstatement(qid, pid, pname, str, viaf_cluster);
	mw.claim_id++;
}

/**
 * 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 - added 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

}); // end of mw.loader.using