User:קיין ומוויסנדיק פּרעפֿערענצן/authority control.js

From Wikidata
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)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
var wd_authority_control = {

	q_prefix:'Q',
	p_prefix:'P',
	birth_year:'',
	death_year:'',
	broken_gnd: {},

	id : 'authority_control_results' ,
	api : '/w/api.php' ,
	site_api : '/w/index.php' ,
	allowedCodes : {
		WKP:{key:'WKP',p:0} ,
		RSL:{key:'RSL',p:947} ,
		NSZL:{key:'NSZL',p:951} ,
		BNE:{key:'BNE',p:950} ,
		BNC:{key:'BNC',p:1273} , /* BNC = CANTIC */
		BIBSYS:{key:'BIBSYS',p:1015} , /* "Norway (BIBSYS)" ; [[viaf:106122570]] */
		BAV:{key:'BAV',p:1017} , /* "Vatican Library" ; WMF: 'la' */
		EGAXA:{key:'EGAXA',p:1309} , /* "Bibliotheca Alexandrina (Egypt)" ; [[viaf:102319859]] */
		xA:{key:'xA',p:0} ,
		VIAF:{key:'VIAF',p:214} ,
		DNB:{key:'GND',p:227} ,
		GND:{key:'GND',p:227} ,
		PND:{key:'GND',p:227} ,
		LC:{key:'LCCN',p:244} ,
		LCCN:{key:'LCCN',p:244} ,
		SUDOC:{key:'SUDOC',p:269} ,
		NDL:{key:'NDL',p:349} ,
		NUKAT:{key:'NUKAT',p:1207} , /* "NUKAT Center (Poland)" ; Ludwik Lejzer Zamenhof ([[Q11758]]) [[viaf:73885295]] */
		CINII:{key:'CINII',p:271} ,
		ISNI:{key:'ISNI',p:213} ,
		JPG:{key:'ULAN',p:245} ,
		ULAN:{key:'ULAN',p:245} ,
		SELIBR:{key:'LIBRIS',p:906} ,
		LIBRIS:{key:'LIBRIS',p:906} ,
		NLA:{key:'NLA',p:409} ,
		NKC:{key:'NKC',p:691} ,
		ICCU:{key:'ICCU',p:396} ,
		BNF:{key:'BNF',p:268} ,
		BPN:{key:'BPN',p:651} ,
		NLI:{key:'NLI',p:949} , /* National Library of Israel */ 
		// NLR:{key:'NLR',p:1003} , /* "National Library of Romania */
		PTBNP:{key:'PTBNP',p:1005} , /* "Biblioteca Nacional de Portugal" */
		NTA:{key:'NTA',p:1006} , /* "National Library of the Netherlands" */
		N6I:{key:'N6I',p:1946} , /* National Library of Ireland */
		LAC:{key:'LAC',p:1670} , /* Library of Canada */
		ORCID:{key:'ORCID',p:496}
	} ,

	searching_viaf:false,
	searched_name: '',

	init : function () {
		const self = this ;
		console.log("initialization of not so global authority control");
		//var nextNode = UTCLiveClockConfig.nextNodeId ? document.getElementById( UTCLiveClockConfig.nextNodeId ) : undefined;
		let portletLink = mw.util.addPortletLink(
			'p-personal',
			'#',
			'Authority Control',
			'utcdate',
			null,
			null,
			undefined
		);
		if ( !portletLink ) {
			return;
		}

		$(portletLink).click ( function () {
			self.run() ;
			return false ;
		} ) ;

	} ,
	
	run : function () {
		const self = this ;
		//self.name = $( '.wb-firstHeading' ).find( '.wikibase-labelview-text' ).text();
		self.name = $('h1 span.wikibase-title-label').text().replace(/\([PQ]\d+\)$/,'') ;
		$('#'+self.id).remove() ;
		$('#mw-content-text').before ( "<div id='"+self.id+"' title='Authority control' style='overflow:auto'><div id='"+self.id+"_content'></div></div>" ) ;
		$('#'+self.id).dialog ( {
			modal : true ,
			height:'auto' ,
			width : 'auto',
			position: { my: "left top", at: "left top", of: window }
		} ) ;
//		$($('div.wb-claims-section').get(0)).before ( "<div style='padding:2px;margin:2px;border:5px solid #DDDDDD;position:relative' id='"+self.id+"'></div>" ) ;
		self.results = [] ;
		$.each ( ['en','de','fr','ja','es','commons'] , function ( k , v ) { self.lookOnWP ( v ) ; } ) ;

		let dates ;
		self.birth_year = $($('#P569 .wikibase-snakview-variation-valuesnak').get(0)).text().replace(/^.*?(\d{3,4}).*$/,'$1') ;
		self.death_year = $($('#P570 .wikibase-snakview-variation-valuesnak').get(0)).text().replace(/^.*?(\d{3,4}).*$/,'$1') ;
		if (''+self.birth_year+self.death_year){
			dates = `${self.birth_year} ${self.death_year}`;
		}
		self.lookOnVIAF ( self.name , dates ) ;
	} ,
	getNodeName : function ( name ) { // Node name; there is a bug with Chrome, but recent jQuery update removed $.browser
		var self = this ;
		return `ns${viaf_record_counter}\\:${name}` ;
	} ,


	gotJSON : function ( data ) {
	//	console.log ( data ) ;
	} ,

	lookOnVIAF : function ( name , dates ) {
		// second request: look viaf for missing parts
		const self = this ;
		if ( !self.searching_viaf ) {
			self.viaf_num = self.results.length ;
			self.results.push ( { source:'viaf.org' , status:'searching' , data:[] } ) ;
			self.updateResults(1) ;
			self.searching_viaf = true ;
		}
		
		var r = Math.random() ;

        // remove diacritics from name
		var search_key = name.normalize("NFD").replace(/[\u0300-\u036f]/g, "") ;
		self.searched_name = search_key;
		if ( typeof dates != 'undefined' ) search_key += ' ' + dates ;

		$.ajax ( {
			dataType: "json",
			url : '//tools.wmflabs.org/magnustools/authority_control.php?callback=?' ,
			data : { query : 'viaf' , key : search_key , r:Math.random() } ,
			timeout : 15000 ,
			error : function () {
				alert ( "VIAF or WMF Labs have a problem; no VIAF data at this time. Maybe later.") ;
			} ,
			success : function ( d ) {
            viaf_record_counter=1;
			$($.parseXML ( d.result )).find('record').each ( function ( id , record ) {
				r = $(record) ;
                viaf_record_counter++ ;
//				if ( !$.browser.chrome ) console.log ( r )
				var data = { ids : [] , comment : [] } ;
				
				data.birth_date = $(r.find(self.getNodeName('birthDate'))).text() ;
				data.death_date = $(r.find(self.getNodeName('deathDate'))).text() ;

				var viaf = r.find(self.getNodeName('viafID')).text() ;
				data.ids.push ( { code:'VIAF' , value:viaf } ) ;
				data.page = "http://viaf.org/viaf/" + viaf + "/" ;

				r.find(self.getNodeName('source')).each ( function ( k , v ) {
					if ( ($(v).attr('differentiated')||'').toLowerCase() == 'false' ) return ;
					var n = $(v).text().split('|') ;
					if ( n.length != 2 ) return ;
					if ( undefined === self.allowedCodes[n[0].toUpperCase()] ) return ;
					let thecode = self.allowedCodes[n[0].toUpperCase()].key ;
					data.ids.push ( { code:thecode , value:self.fixCodeValue(thecode,n[1])  } ) ;
//					data.ids[n[0]] = n[1] ;
				} ) ;

				r.find(self.getNodeName('mainHeadings')).each ( function ( k , v ) {
					$($(v).find(self.getNodeName('text'))).each ( function ( k2 , v2 ) {
						data.comment.unshift ( $(v2).text() ) ;
					} ) ;
				} ) ;
				r.find(self.getNodeName('titles')).each ( function ( k , v ) {
					$($(v).find(self.getNodeName('text'))).each ( function ( k2 , v2 ) {
						data.comment.push ( $(v2).text() ) ;
					} ) ;
				} ) ;
				
				data.comment = "<div>" + data.comment.join('</div><div>') + "</div>" ;
				
				self.results[self.viaf_num].data.push ( data ) ;
				
				if ( self.results[self.viaf_num].length >= 10 ) return false ;
				
			} ) ;
			
			if ( self.results[self.viaf_num].data.length === 0 ) {
				if ( typeof dates != 'undefined' ) {
					return self.lookOnVIAF ( name ) ; // Try again, without dates
				}
				self.results[self.viaf_num].status = 'no results' ;
			} else self.results[self.viaf_num].status = 'done' ;
			self.updateResults(-1) ;

		} } ) ;
	} ,
	
	lookOnWP : function ( lang ) {
		const self = this ;
		var rk = self.results.length ;
		var project = lang=='commons'?'wikimedia':'wikipedia' ;
		self.results.push ( { source:(lang=='commons'?lang:lang+'.'+project) , status:'searching' , data:[] } ) ;
		self.updateResults() ;
		var article ;
		if ( lang == 'commons' ) {
			article = 'Creator:'+self.name ;
		} else {
			var lookfor = 'https://' + lang + '.'+project+'.org/wiki/' ;
			$('div.wikibase-sitelinkgrouplistview a').each ( function () {
				var href = $(this).attr('href') ;
				if ( undefined === href || href.substr(0,lookfor.length) != lookfor ) return ;
				article = $(this).text() ;//href.substr(lookfor.length) ;
				return false ;
			} ) ;
		}
		
		if ( undefined === article ) {
			self.results[rk].status = 'no article' ;
			self.updateResults() ;
			return ;
		}

		self.running++ ;
		$.getJSON ( "//" + lang + "."+project+".org/w/api.php?callback=?" , {
			action : 'query' ,
			prop : 'revisions' ,
			titles : article ,
			rvprop : 'content|timestamp' ,
			format : 'json'
		} , function ( d ) {
			$.each ( d.query.pages , function ( k , v ) {
				if ( v.revisions === undefined ) {
					self.results[rk].status = 'no article' ;
					self.updateResults(-1) ;
					return ;
				}
				var t = v.revisions[0]['*'].replace ( /\s+/g , ' ' ) ;
				
				if ( self.birth_year+self.death_year == '' ) {
					var m ;
					m=t.match(/:(\d+)[_ ]births\s*\]\]/); if(m!=null)self.birth_year=m[1] ;
					m=t.match(/:(\d+)[_ ]deaths\s*\]\]/); if(m!=null)self.death_year=m[1] ;

					m=t.match(/:[Gg]eboren[_ ](\d+)\s*\]\]/); if(m!=null)self.birth_year=m[1] ;
					m=t.match(/:[Gg]estorben[_ ](\d+)\s*\]\]/); if(m!=null)self.death_year=m[1] ;

					m=t.match(/:[Nn]aissance[_ ]en[_ ](\d+)\s*\]\]/); if(m!=null)self.birth_year=m[1] ;
					m=t.match(/:[Dd]écès[_ ]en[_ ](\d+)\s*\]\]/); if(m!=null)self.death_year=m[1] ;

					m=t.match(/:[Nn]acidos[_ ]en[_ ](\d+)\s*\]\]/); if(m!=null)self.birth_year=m[1] ;
					m=t.match(/:[Ff]allecidos[_ ]en[_ ](\d+)\s*\]\]/); if(m!=null)self.death_year=m[1] ;

					m=t.match(/\{\{NF\|(\d+)\|(\d+)/); if(m!=null){self.birth_year=m[1] ; self.death_year=m[2] ;}
				}
					
				

				var st = null ;
				if ( lang == 'en' || lang == 'commons' ) st = t.match ( /{{Authority[ _]control(.+?)}}/i ) ;
				else if ( lang == 'de' ) st = t.match ( /{{Normdaten(.+?)}}/i ) ;
				else if ( lang == 'ja' ) st = t.match ( /{{Normdaten(.+?)}}/i ) ;
				else if ( lang == 'fr' ) st = t.match ( /{{Autorité\s*\|(.+?)}}/i ) ;
				if ( st != null ) {
					var kv = {} ;
					var data = [] ;
					$.each ( st[1].split ( '|' ) , function ( dummy , kvp ) {
						var m = kvp.match ( /^\s*([a-z]+)\s*=\s*(.+?)\s*$/i ) ;
						if ( m == null ) return ;
						var code = $.trim(m[1]).toUpperCase() ;
						if ( undefined === self.allowedCodes[code] ) return ;
						var value = self.fixCodeValue ( code , m[2] ) ;
						data.push ( { code:code , value:value } ) ;
					} ) ;
					self.results[rk].data.push ( { ids:data , comment:"From authority control template" } ) ;
				}
				if ( self.results[rk].data.length == 0 ) self.results[rk].status = 'no results' ;
				else self.results[rk].status = 'done' ;
				self.updateResults(-1) ;
			
			} ) ;
		} ) ;
			
	} ,
	
	fixCodeValue : function ( code , value ) {
		value = $.trim ( value ) ;
		value = value.replace(/\s/g,'');
		
		switch ( code) {
			case 'ICCU':
				var m = value.match ( /(.{2,4})(\d{6})$/ ) ;
				if ( m != null ) {
					value = 'IT\\ICCU\\'+m[1]+'\\'+m[2] ;
				}
				break
			case 'LCCN':
				var m = value.match ( /^(.+)\/(\d+)\/(\d+)/ ) ;
				if ( m != null ) {
					while ( m[3].length < 6 ) m[3] = '0' + m[3] ;
					value = m[1] + '/' + m[2] + '/' + m[3] ;
				}
				value = value.replace(/\//g,'') ;
				break
			case 'RSL':
				value = value.replace ( /^nafpn-/i , '' ) ;
				break
		    case 'ISNI':
				var v = '' ;
				while ( value.length > 0 ) {
					if ( v != '' ) v += ' ' ;
					v += value.substr ( 0 , 4 ) ;
					value = value.substr ( 4 , value.length-4 ) ;
				}
				value = v ;
				break;
			case 'BNF':
				value = 'cb' + value.replace ( /\D/g , '' ) ; // 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 i=0; i < value.length; i++){
			        bnf_check_digit += bnf_xdigits.indexOf(value[i]) * (i+1);
	    		}
	    		value = value.substr(2) + bnf_xdigits[bnf_check_digit % bnf_xdigits.length]; //29 is the radix
	    		break
			case 'EGAXA':
				value = value.replace ( /^vtls/i , '' ) ;
				break
			case 'NLA':
				value = value.replace ( /^0+/i , '' ) ;
				break
		}
		return value ;
	} ,
	
	updateResults : function ( d ) {
		let self = this ;
		if ( d !== undefined ) self.running += d ;
		let dialog_wrapper = document.createElement("div");
		// h=result
		if ( self.birth_year !== '' || self.death_year !== '' ) {
			let birthdata = document.createElement("div");
			dialog_wrapper.appendChild(birthdata);
			birthdata.style.font = '14pt'; 
			birthdata.innerHTML = `${self.name} (${self.searched_name}) (${self.birth_year||'?'} &ndash; ${self.death_year||'?'})`;
		}
		let info_table = document.createElement("table");
		dialog_wrapper.appendChild(info_table);
		info_table.style.borderCollapse = "collapse";
		info_table.style.border = "1px solid black";
		let info_table_header = info_table.createTHead();
		info_table_header.innerHTML = "<tr style='border:2px solid black'><th style='border:2px solid black'>Source</th><th style='border:2px solid black' colspan=4>Result</th></tr>" ;
		let info_table_body = info_table.createTBody();
		$.each ( self.results , function ( k , v ) {
			var rows = 0 ;
			$.each ( v.data , function ( k2 , v2 ) { rows += v2.ids.length } ) ;
			if ( rows == 0 ) rows = 1 ;
			if ( v.data.length == 0 ) {
				let table_row = info_table_body.insertRow();
				let cell = table_row.insertCell();
				cell.rowSpan = rows;
				cell.style.border = "1px solid black";
				cell.style.padding = "2px";
				cell.style.verticalAlign = 'top';
				cell.innerText = v.source;

				cell = table_row.insertCell();
				cell.colSpan = 4;
				cell.style.border = "1px solid black";
				cell.style.padding = "2px";
				cell.style.verticalAlign = 'top';
				cell.style.fontStyle = 'italic';
				cell.innerText = v.status;
				if ( v.status == 'searching' ){
					cell.style.color = '#2DC800';
				}
			} else {
				let table_row = info_table_body.insertRow();
				let start_cell = table_row.insertCell();
				start_cell.rowSpan = rows;
				start_cell.style.border = "1px solid black";
				start_cell.style.padding = "2px";
				start_cell.style.verticalAlign = 'top';
				start_cell.innerText = v.source;
				$.each ( v.data , function ( k1 , v1 ) {
					if ( k1 != 0 ) table_row = info_table_body.insertRow();
					$.each ( v1.ids , function ( k2 , v2 ) {
						if ( k2 > 0 ) table_row = info_table_body.insertRow() ;
						else {
							cell = table_row.insertCell();
							cell.rowSpan = v1.ids.length;
							cell.style.border = "1px solid black";
							cell.style.verticalAlign = 'top';
							let h = `<a href='#' style="font-size:1.5rem; background-color:lightblue" title='Add these AC data to the item' onclick='wd_authority_control.addSet(${k},${k1});return false'>+</a>` ;
							if ( v1.page !== undefined ) h += `<br/><a title='Show original data in new tab' target='_blank' href='${v1.page}' style='font-size:14pt'>&rArr;</a>` ;
							cell.innerHTML = h ;
						}
						cell = table_row.insertCell();
						cell.style.padding = "2px";
						cell.style.border = "1px solid black";
						cell.innerText = v2.code ;
						
						cell = table_row.insertCell();
						cell.style.padding = "2px";
						cell.style.border = "1px solid black";
						cell.style.whiteSpace = "nowrap";
						
						let p = self.allowedCodes[v2.code].p ;
						var exp = $(`div.wb-claim-section-P${p} div.valueview-value`);
						let add_item_link = `&nbsp;<a href='#' style="font-size:1.5rem; background-color:lightblue" title='Add this to the item' onclick='wd_authority_control.addSet(${k1},${k1},${k2});return false'>+</a>` ;
						if (v2.code == "GND" && !self.checkGND(v2.value)){
							add_item_link = "&nbsp;–––––" ;
						}
						if ( exp.length == 0 ){
							if(v2.code == "WKP"){
								let link = `https://www.wikidata.org/wiki/${v2.value}`;
								let col2 = (window.location.href.indexOf(link) > -1) ? "green" : "red";
								cell.innerHTML = `<a href="${link}" style="color:${col2}">${v2.value}</a>` ;
							}else {
								cell.innerHTML = `${v2.value}${add_item_link}` ;
							}
						} else {
							let identical = false ;
							exp.each ( function ( ek , ev ) {
								var t = $(ev).text().replace(/\s/g,'') ;
								if ( t == '' ) t = $($(ev).find('textarea')).val().replace(/\s/g,'') ;
								if ( $.trim(t.replace(/[ \/]/g,'')) == $.trim(v2.value.replace(/[ \/]/g,'')) ) identical = true ;
							} ) ;
							let color = identical ? 'blue' : 'red' ;
							if(v2.code == "WKP"){
								let link = `https://www.wikidata.org/wiki/${v2.value}`;
								// overwrite check
								color = (window.location.href.indexOf(link) > -1) ? "green" : "red" ;
								h = `<a href="${link}" style="color:${color}">${v2.value}</a>` ;
							} else {
								h = `<span style='color:${color}'>${v2.value}</span>` ;
							}
							if ( !identical ) {
								if ( p == 0 ) h += "&nbsp;<span title='This property is not yet available on Wikidata, but might soon be!'>&times;</span>" ;
								else h += add_item_link ;
							}
							cell.innerHTML = h
						}
						
						if ( k2 == 0 ) {
							cell = table_row.insertCell();
							cell.style.border = "1px solid black";
							cell.style.padding = "2px";
							cell.style.verticalAlign = 'top';
							cell.rowSpan = v1.ids.length;
							let innerElement;
							if ( v1.page !== undefined ){
								innerElement = document.createElement("a");
								innerElement.target = '_blank';
								innerElement.href = v1.page;
							}
							else {
								innerElement = document.createElement("div");
							}
							innerElement.style.maxHeight = "100px";
							innerElement.style.overflow = "auto";
							innerElement.style.fontSize = "8pt";
							innerElement.style.maxWidth = "600px";
							if ( v1.birth_date !== undefined || v1.death_date !== undefined ) {
								var hd = "<div>" + (v1.birth_date||'?') + " &ndash; " + (v1.death_date||'?') + "</div>" ;
								if ( self.birth_year !== '' ) hd = hd.replace ( self.birth_year , '<b>'+self.birth_year+'</b>' ) ;
								if ( self.death_year !== '' ) hd = hd.replace ( self.death_year , '<b>'+self.death_year+'</b>' ) ;
								innerElement.innerHTML = hd + "<br/>" + v1.comment;
							} else {
								innerElement.innerHTML = v1.comment;
							}
							cell.appendChild(innerElement);
						}
					} ) ;
				} ) ;
			}
		} ) ;
		let info_table_footer = info_table.createTFoot();
		info_table_footer.innerHTML = "<tr><td style='padding:2px' colspan=5><b>Legend:</b>&nbsp;<span style='color:blue'>Already in item</span>&nbsp;<span style='color:red'>Contradicts item</span></td></tr>" ;
		$('#'+self.id+'_content').html ( dialog_wrapper.innerHTML ) ;
		$('#'+self.id).dialog ( {
			modal : true ,
			height:'auto' ,
			width : 'auto',
			position: { my: "left top", at: "left top", of: window }
			}) ;
	} ,
	
	checkGND: function(gndid){
		if (this.broken_gnd[gndid] === undefined){
			let res = $.ajax({
		        type: "POST",
		        url: "http://localhost:5555",
		        data: {
		        	url: `https://d-nb.info/gnd/${gndid}`
		        },
		        async: false,
		        crossDomain: true
		    });
			if (!res.responseJSON["error"] && res.responseJSON["size"] > 0){
		    	this.broken_gnd[gndid] = true;
		    }
		    this.broken_gnd[gndid] = false;
		}
		return this.broken_gnd[gndid];
	} ,
	
	addSet : function ( k1 , k2 , k3 ) {
		const self = this ;
		self.claims2add = [] ;
		if ( k3 === undefined ) {
			$.each ( self.results[k1].data[k2].ids , function ( k3 , v3 ) {
				var p = self.allowedCodes[v3.code].p ;
				self.claims2add.push ( [ p , v3.value ] ) ;
			} ) ;
		} else {
			var v3 = self.results[k1].data[k2].ids[k3] ;
			var p = self.allowedCodes[v3.code].p ;
			self.claims2add.push ( [ p , v3.value ] ) ;
		}
		$('#'+self.id).css ( { 'background-color' : '#444444' } ) ;
		self.setNextClaim() ;
	} ,
	
	setNextClaim : function () {
		const self = this ;
		if ( self.claims2add.length == 0 ) {
			$('#'+self.id).css ( { 'background-color' : '' } ) ;
			return ;
		}
		var x = self.claims2add.shift() ;
		if ( x[0] == 0 ) self.setNextClaim() ; // Future property
		else self.tryCreateClaim ( x[0] , x[1] ) ;
	} ,

	tryCreateClaim : function ( property , value ) {
		const self = this ;
		if(property==self.allowedCodes['GND'].p && !self.checkGND(value)){
			return;
		}
		var entity = mw.config.get('wgTitle') ;
		//console.log ( "Property " + property + " : " + value ) ;
		property += '' ;
		value += '' ;
		entity = self.q_prefix + entity.replace ( /\D/g , '' ) ;
		property = property.replace ( /\D/g , '' ) ;
		$.getJSON ( self.api , {
			action : 'wbgetentities' ,
			format : 'json' ,
			ids : entity ,
			props : 'info|claims'
		} , function ( data ) {
			if ( undefined !== data.entities[entity] ) {
				if ( undefined !== data.entities[entity].claims ) {
					if ( undefined !== data.entities[entity].claims[self.p_prefix+property] ) {
						var n = data.entities[entity].claims[self.p_prefix+property] ;
						var exists = false ;
						$.each ( n , function ( k , v ) {
							if ( v.mainsnak.datavalue.value == value ) {
								exists = true ;
								return false ;
							}
						} ) ;
						if ( exists ) {
							console.log ( "p"+property+' exists for '+entity ) ;
							self.setNextClaim() ;
							return ;
						}
					}
				}
			}
//			console.log ( "Claiming " + property + " : " + value ) ;
			self.createClaim ( entity , property , value ) ;
		} ) ;
	} ,
		
		
	createClaim : function ( entity , property , value ) {
		console.log ( "Creating " + entity + " / " + property + " / " + value ) ;
		const 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.setNextClaim() ;
				return ;
			}
			
			property = property.replace(/\D/g,'') ;
			entity = entity.replace(/\D/g,'') ;
//			var vo = JSON.parse ( value ) ;
//			var value_id = vo['numeric-id']+'' ;
			
			$.post ( self.api , {
				action : 'wbcreateclaim' ,
				entity : self.q_prefix+entity ,
				snaktype : 'value' ,
				property : self.p_prefix+property ,
				value : JSON.stringify ( value ) ,
				token : token ,
				baserevid : lastrevid ,
				format : 'json'
			} , function ( data ) {
				var id = 'added_' + self.id_cnt ;
				var h = "<div class='wb-claim-section-P"+property.replace(/\D/g,'')+"'>Added AC data : <div style='display:inline-block' class='valueview-value'>"+value+"</div></div>" ;
				$($('div.wb-claims').get(0)).append ( h ) ;
				self.updateResults() ;
				self.setNextClaim() ;
				$.get(`${site_api}?title=Q${entity}&action=purge&forcelinkupdate=true`, {}, function (data) {
						console.log(`Purge of Q${entity} successful`)
					}
				)
			} , 'json' ) ;
			
			
			
		} , 'json' ) ;
	
	} ,
	fin : true
} ;

jQuery(document).ready ( function() {
	if ( mw.config.get('wgNamespaceNumber') != 0 ) return ;
	if ( mw.config.get('wgAction') != 'view' ) return ;

	mw.loader.using( 'jquery.ui' ).then( function () {
		wd_authority_control.init () ;
	} ) ;
});