User:Vennor/it.wiki infobox.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]], [[User:Magnus_Manske/import_statements.js]], [[User:Goldzahn/wikidata_useful.js]]

/*
* [[User:Viscontino/it.wiki infobox.js]]
* Mostra alcuni dati reperiti dall'infobox presente nella voce su it.wiki.
* Per il momento funziona soltanto con i comuni italiani... poi si vedrà :)
*/

 
function ucFirst(string) {
	return string.substring(0, 1).toUpperCase() + string.substring(1);
}

var wd_useful = {

        infobox2statement : {
		'Divisione amministrativa' : [
                        { key:'Panorama' , statement:'immagine' , type:'media' , pid:18 } ,
			{ key:'Bandiera' , statement:'bandiera' , type:'media' , pid:41 } ,
			{ key:'Stemma' , statement:'stemma' , type:'media' , pid:94 } ,
			{ key:'Divisione amm grado 2' , statement:'unità amministrativa in cui è situato' , type:'item' , pid:131 } ,
                        { key:'Amministratore locale' , statement:'capo del governo locale' , type:'item' , pid:6 } ,
			{ key:'Codice postale' , statement:'codice postale' , type:'stringvalue' , pid:281 } ,
			{ key:'Sottodivisioni' , statement:'sottodivisioni amministrative' , type:'item' , pid:150 } ,
                        { key:'Divisioni confinanti' , statement:'confina con' , type:'item' , pid:47 } ,
			{ key:'Mappa' , statement:'mappa di localizzazione' , type:'media' , pid:242 }
		] 
	} ,
 
	id_cnt : 0 ,
	api : '/w/api.php' ,
           
	init : function () {
		var self = this ;
		var q = mw.config.get('wgPageName').toLowerCase() ;
		self.q = q ;
		self.queue = [] ;
 
		$.getJSON ( '//www.wikidata.org/w/api.php?callback=?' , {
			action : 'wbgetentities' ,
			ids : q ,
			format : 'json' ,
			sites : 'sites' ,
			props : 'sitelinks'
		} , function ( data ) {
			if ( undefined === data.entities[q] || undefined === data.entities[q].sitelinks || undefined === data.entities[q].sitelinks.itwiki ) {
				alert ( "Nulla trovato nella voce su it.wikipedia, annullo" ) ;
				return ;
			}
			var title = data.entities[q].sitelinks.itwiki.title ;
			self.loadStatements ( 'it.wikipedia' , title ) ;
		} ) ;
	} ,

	loadStatements : function ( wiki , title ) {
                console.log ( "LoadStatements title: " +title );
		var self = this ;
		$.getJSON ( '//' + wiki + '.org/w/api.php?callback=?' , {
			action : 'parse' ,
			page : title ,
			format : 'json' ,
			prop : 'wikitext|categories'
		} , function ( data ) {
			if ( undefined === data.parse.wikitext ) {
				return ;
			}
			self.categories = [] ;
			$.each ( data.parse.categories , function ( k , v ) {
				self.categories.push ( v['*'] ) ;
			} ) ;
			self.tree = { type : 'page' , children : [] } ;
			var text = data.parse.wikitext['*'].replace(/\n/gm,' ') ;
			self.growTree ( text , self.tree ) ;
			self.templates = [] ;
			self.parseTemplatesFromTree ( self.tree ) ;
			self.prepareStatements () ;
		} ) ;
	} ,
 
	standardizeTemplateName : function ( s ) {
		return ucFirst ( s.replace(/^\s+/,'').replace(/\s+$/,'').replace(/_/g,' ') ) ;
	} ,
 
	parseTemplatesFromTree : function ( tree ) {
		var self = this ;
		$.each ( (tree.children||[]) , function ( k , v ) {
			self.parseTemplatesFromTree ( v ) ;
		} ) ;
 
		if ( tree.type !== '{{' ) { return; }
 
		var t = { name : '' , params : {} , orig:self.renderTree(tree) } ;
		var pcnt = 1 ;
		var is_new_field = false ;
		$.each ( tree.children , function ( k , v ) {
			if ( k == 0 ) {
				t.name = self.standardizeTemplateName ( v.text ) ;
				return ;
			}
 
			if ( v.newfield ) {
				is_new_field = true ;
				return ;
			}
 
			if ( is_new_field ) {
				is_new_field = false ;
				var nt = v.text ;
				var m = nt.match ( /^\s*([^=]+?)\s*=(.+)$/ ) ;
				var p = {} ;
				if ( m == null ) {
					p.key = pcnt++ ;
					p.value = nt ;
				} else {
					p.key = m[1] ;
					p.value = m[2] ;
				}
				last_key = p.key ;
				t.params[p.key] = p.value ;
			} else {
				t.params[last_key] += self.renderTree ( v ) ;
			}
 
		} ) ;
 
		self.templates.push ( t ) ;
	} ,
 
	renderTree : function ( tree ) {
		var self = this ;
		var ret = (tree.type||'') ;
		if ( undefined !== tree.text ) ret += tree.text ;
		$.each ( (tree.children||[]) , function ( k , v ) {
//			if ( tree.type == '{{' && k > 0 ) ret += "|" ;
			ret += self.renderTree ( v ) ;
		} ) ;
		return ret + (tree.close||'') ;
	} ,
 
	growTree : function ( text , tree ) {
		var self = this ;
		var p = 0 ;
		var t = '' ;
		while ( p < text.length ) {
			var s = text.substr ( p , 2 ) ;
                        if ( s == '[[' ) {
                               /* text = text.replace(/\[\[(.+?[^\|].+?)\]\]/,'$1'); // elimino parantesi senza pipe (la prima incontrata), se c'è
                                if(s == text.substr(p,2)){ // se non è cambiato nulla
                                    text = text.replace(/\[\[/g,'').replace(/\|(.*?\]\])/g,''); // elimino il problema del pipe: "|xxx]]"
                                }*/
                                text = text.replace(/\[\[([^\]]+?)\|{1}(.+?)\]\]/g,'$1').replace(/\[\[([^\|]+?)\]\]/g,'$1');
                                t += text[p] ;
				p++ ;
			} else if ( s == '{{' || s == '{|' ) {
				if ( t !== '' ) { tree.children.push ( { text:t } ) ; t = '' ; }
				var node = { type : s , children : [] } ;
				text = self.growTree ( text.substr ( p+2 ) , node ) ;
				p = 0 ;
				tree.children.push ( node ) ;
			} else if ( s == '}}' || s == '|}' || s == ']]' ) {
				if ( t !== '' ) { tree.children.push ( { text:t } ) ; t = '' ; }
				tree.close = s ;
				return text.substr ( p+2 ) ;
			} else if ( tree.type == '{{' && text[p] == '|' ) {
				if ( t !== '' ) tree.children.push ( { text:t } ) ;
				t = '' ;
				tree.children.push ( { text:t , newfield:true } ) ;
				p++ ;
			} else {
				t += text[p] ;
				p++ ;
			}
		}
		if ( t !== '' ) tree.children.push ( { text:t } ) ;
		return '' ;
	} ,

	prepareStatements : function () {
		var self = this ;
		self.queue = [] ;
		self.imported = 0 ;
		$.each ( self.templates , function ( k1 , v1 ) {
			if ( undefined === self.infobox2statement[v1.name] ) { return; }
			$.each ( self.infobox2statement[v1.name] , function ( k2 , v2 ) {
				if ( undefined === v1.params[v2.key] ) { return; }
				self.queue.push ( { type:v2.type , statement:v2.statement , value:v1.params[v2.key] , prop_id:v2.pid } ) ;
			} ) ;
		} ) ;
		self.processNextQueueItem2() ;
	} ,

        processNextQueueItem2 : function () {
                var self = this ;
/*              if ( self.queue.length == 0 ) {
			alert ( "Infoboxes scanned, " + self.imported + " statements imported" ) ;
			return ;
		}
*/

                var h = "<div style='position:absolute;right:5px;top:5px;z-index:5;word-wrap: break-word;width: 280px;'>" ;
		h += "<div>This is V0.01:" ;
		h += "<ul>";
                
		var q = self.queue.shift() ;

                h += "<li>"+(self.queue.length+1)+". tipo di divisione amministrativa: <a href='#' onclick='wd_useful.thisIs(\"tipo di divisione amministrativa\");return false'>comune</a></li>";

                do {
        //console.log("Sto facendo: "+q.statement);
			if ( q.type == 'item' ) {
				//console.log ( "TODO : Item ; Dichiarazione : " +q.statement+ " ; Valore : " +q.value ) ;
				//self.setStatementItem ( q.statement , q.value , q.prop_id ) ;
                
                        	//h += "<li>"+self.queue.length+". "+q.statement+": <a href='#' onclick='wd_useful.thisIs(\""+q.statement+"\");return false'>"+q.value+"</a></li>";
var d;
                                if(q.statement == 'unità amministrativa in cui è situato') {
                                       q.value = "Provincia di "+q.value;}
        /*console.log("Sto facendo: "+q.statement+", dovrei essere nella "+q.value);
                                       $.getJSON ( '//www.wikidata.org/w/api.php?callback=?' , {
			                              action : 'wbgetentities' ,
			                              titles : q.value ,
			                              format : 'json' ,
			                              sites : 'itwiki'
		                               } , function ( data ) {
			                              console.log(q.statement+"   "+q.value+"   "+Object.keys(data.entities)[0]);
//console.log(typeof Object.keys(data.entities)[0] === 'string');
                                                      h += "<li>"+self.queue.length+". "+q.statement+": <a href='#' onclick='wd_useful.thisIs(\""+q.statement+"\",\""+Object.keys(data.entities)[0]+"\");return false'>"+q.value+"</a></li>";
                                               }
		                       );
                                 } else {*/
                                      h += "<li>"+self.queue.length+". "+q.statement+": "+q.value+"</li>";
                                 //}
                	} else if ( q.type == 'media' ) {
                        	//console.log ( "TODO : Media ; Dichiarazione : " +q.statement+ " ; Valore : " +q.value ) ;
				//self.setStatementItem ( q.statement , q.value , q.prop_id ) ;
                
                        	//h += "<li>"+self.queue.length+". "+q.statement+": <a href='#' onclick='wd_useful.thisIs(\""+q.statement+"\");return false'>"+q.value+"</a></li>";
                                h += "<li>"+self.queue.length+". "+q.statement+": "+q.value+"</li>";
                	} else if ( q.type == 'stringvalue' ) {
                        	//console.log ( "TODO : StringValue ; Dichiarazione : " +q.statement+ " ; Valore : " +q.value ) ;
				//self.setStatementItem ( q.statement , q.value , q.prop_id ) ;
                
                        	//h += "<li>"+self.queue.length+". "+q.statement+": <a href='#' onclick='wd_useful.thisIs(\""+q.statement+"\");return false'>"+q.value+"</a></li>";
                                h += "<li>"+self.queue.length+". "+q.statement+": "+q.value+"</li>";
                	}
                	q = self.queue.shift() ;
                }while(self.queue.length !== 0 );
                
                //h += "<li>"+self.queue.length+". "+q.statement+": <a href='#' onclick='wd_useful.thisIs(\""+q.statement+"\");return false'>"+q.value+"</a></li>";
                h += "<li>"+self.queue.length+". "+q.statement+": "+q.value+"</li>";

                h += "</ul></div>";
                $('#mw-content-text').append ( h ) ;

                /*self.pullCookies();
		self.tryDesc() ;
		self.autoName() ;
		self.tryAutoAdd() ;
		self.autoRenameStatements () ;
		self.showQ() ;*/
	} ,

        pullCookies : function ( ) {
               document.getElementById('input11-neu').value = $.cookie('p_value');
               document.getElementById('input21-neu').value = $.cookie('q_value21');
               document.getElementById('input22-neu').value = $.cookie('q_value22');

               document.getElementById('elem').num = '0'; // Set variable to '0' 
               document.getElementById('elem11').num = '0';
               document.getElementById('elem21').num = '0';
               document.getElementById('elem22').num = '0';
	} ,

	autoRenameStatements : function () {
		var self = this ;
		entity = 'q' + self.q.replace ( /\D/g , '' ) ;
		$.getJSON ( self.api , {
			action : 'wbgetentities' ,
			format : 'json' ,
			ids : entity ,
			props : 'info|claims'
		} , function ( data ) {
			if ( undefined === data.entities[entity] ) { return; }
			if ( undefined === data.entities[entity].claims ) { return; }
			$.each ( data.entities[entity].claims , function ( p , v ) {
				if ( p=='p28'|p=='p11'||p=='p12'||p=='p28'||p=='p83'||p=='p34' ) { // replacing deprecated properties with "located in administrative unit"
					self.replaceClaimProperty ( { old_prop : p , new_prop : 'p131' , claim : v } ) ;
				}
			} ) ;
			self.processNextQueueItem () ;
		} ) ;
	} ,
 
	replaceClaimProperty : function ( data ) {
		var self = this ;
		$.each ( data.claim , function ( k , v ) {
			var nid = v.mainsnak.datavalue.value['numeric-id'] ;
//			console.log ( data.old_prop + " => " + data.new_prop + " : " + nid ) ;
			self.queue.push ( { mode:'set' , prop:data.new_prop , target_entity:'q'+nid } ) ;
			self.queue.push ( { mode:'remove' , prop:data.old_prop , target_entity:'q'+nid } ) ;
		} ) ;
	} ,
 
	showQ : function () {
		$('div.valueview-value a').each ( function ( k , v ) {
			var url = $(v).attr('href') || '' ;
			var m = url.match ( /\/[qQ](\d+)$/ ) ;
			if ( m != null ) {
				var h = " <span style='color:#999999'><i>q" + m[1] + "</i></span>" ;
				$(v).after ( h ) ;
			}
		} ) ;
	} ,
 
 
	tryAutoAdd : function () {
		var self = this ;
		$('.wb-property-container-value .wb-value').each ( function ( k , v ) {
			var t = $(v).text() ;
			if ( t == 'Wikipedia disambiguation page' ) self.thisIs ( 'disambig' ) ;
		} ) ;
	} ,
 
	tryDesc : function () {
		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 ) ;
			} ) ;
		} ) ;
	} ,
 
        thisIs : function ( what , w2 ) {
		var self = this ;
//		if ( self.running ) { return; }
//		self.running = true ;
		if ( what == 'tipo di divisione amministrativa' ) {
			self.queue.push ( { mode:'set' , prop:'p132' , target_entity:'q15284' } ) ;
			self.queue.push ( { mode:'set' , prop:'p107' , target_entity:'q618123' } ) ;
		} else if ( what == 'unità amministrativa in cui è situato' ) {
			self.queue.push ( { mode:'set' , prop:'p107' , target_entity:'q215627' } ) ;
                        self.queue.push ( { mode:'set' , prop:'p131' , target_entity:w2 } ) ;
		} /*else if ( what == 'occupation-1' ) { // <main type> 'person'
			self.queue.push ( { mode:'set' , prop:'p107' , target_entity:'q215627' } ) ;
		} else if ( what == 'occupation-2' ) { // <instance of> 'person'
			self.queue.push ( { mode:'set' , prop:'p31' , target_entity:'q215627' } ) ;
		} else if ( what == 'location' ) {
			self.queue.push ( { mode:'set' , prop:'p107' , target_entity:'q618123' } ) ;
		} else if ( what == 'work' ) {
			self.queue.push ( { mode:'set' , prop:'p107' , target_entity:'q386724' } ) ;
		} else if ( what == 'org' ) {
			self.queue.push ( { mode:'set' , prop:'p107' , target_entity:'q43229' } ) ;
		} else if ( what == 'event' ) {
			self.queue.push ( { mode:'set' , prop:'p107' , target_entity:'q1656682' } ) ;
		} else if ( what == 'term' ) {
			self.queue.push ( { mode:'set' , prop:'p107' , target_entity:'q1969448' } ) ;

		} else if ( what == 'disambig' ) {
			self.queue.push ( { mode:'set' , prop:'p107' , target_entity:'q4167410' } ) ;
		} else if ( what.match ( /^q\d+$/ ) ) { // Is a
			self.queue.push ( { mode:'set' , prop:'p31' , target_entity:what } ) ;
			if ( w2 == 'location' ) self.queue.push ( { mode:'set' , prop:'p107' , target_entity:'q618123' } ) ;
		}*/
		self.processed = 0 ;
		self.processNextQueueItem () ;
		return false ;
	} ,
 
	autoName : function () {
		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 ;
		} ) ;
	} ,
 
	processNextQueueItem : function () {
		var self = this ;
		if ( self.queue.length == 0 ) {
//			self.running = false ;
			if ( self.processed == 0 ) {
//				alert ( "No changes" ) ;
				return ;
			}
			// DONE
			console.log ( "DONE" ) ;
//			location.reload();
			return ;
		}
		var q = self.queue.shift () ;
		if ( undefined === q.entity ) q.entity = self.q ;
		if ( q.mode == 'set' ) {
			var val = '{"entity-type":"item","numeric-id":' + q.target_entity.replace(/\D/g,'') + '}' ;
			self.tryCreateClaim ( q.entity , q.prop , val ) ;
		} else if ( q.mode == 'remove' ) {
			var val = '{"entity-type":"item","numeric-id":' + q.target_entity.replace(/\D/g,'') + '}' ;
			self.tryRemoveClaim ( q.entity , q.prop , val ) ;
		} else {
			console.log ( q ) ;
		}
	} ,
 
	tryCreateClaim : function ( entity , property , value ) {
		var self = this ;
		entity = 'q' + 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 : entity ,
			props : 'info|claims'
		} , function ( data ) {
			if ( undefined !== data.entities[entity] ) {
				if ( undefined !== data.entities[entity].claims ) {
					if ( undefined !== data.entities[entity].claims['p'+property] ) {
						var n = data.entities[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 '+entity ) ;
							self.processNextQueueItem() ;
							return ;
						}
					}
				}
			}
			self.createClaim ( entity , property , value ) ;
		} ) ;
	} ,
 
 
	createClaim : function ( 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' ,
			bot : 1
		} , 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' ,
				bot : 1
			} , function ( data ) {
				var id = 'added_' + self.id_cnt ;
				var h = "<div id='" + id + "'>" ;
				h += "Added " ;
				h += "<span class='added_entity_p'>" + property + "</span>" ;
				h += " &rarr; " ;
				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' ) ;
				self.id_cnt++ ;
 
				self.processed++ ;
				self.processNextQueueItem() ;
			} , 'json' ) ;
 
 
 
		} , 'json' ) ;
 
	} ,
 
	updateEntity : function ( 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 ) ;
		} ) ;
	} ,
 
	the_end : ''
} ;
 
$ ( function() {
	if ( mw.config.get('wgNamespaceNumber') != 0 ) { return; }
	if ( mw.config.get('wgAction') !== 'view' ) { return; }
        
        // solo comuni italiani!
        var desc=JSON.parse(wbEntity);
        if(typeof(desc.descriptions)==='undefined'||typeof(desc.descriptions[wgUserLanguage])==='undefined') { return; }
        else {
	      var desc=desc.descriptions[wgUserLanguage].value;
              if(desc !== "comune italiano") { return; }
              else { console.log("desc: "+desc); wd_useful.init () ; }
        }
});