MediaWiki:Common.js

From Semantic Lab
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)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
if (document.querySelector("#P200")){
  var p200Container = document.querySelector("#P200");
	var p200Container = document.querySelector("#P200");
	var aLinks = p200Container.querySelectorAll("a");
	var urls = [];
	for (var el = 0; el < aLinks.length; el++) {
		if (aLinks[el].getAttribute('href') && (aLinks[el].getAttribute('href').toLowerCase().endsWith('.png') || aLinks[el].getAttribute('href').toLowerCase().endsWith('.jpg') || aLinks[el].getAttribute('href').toLowerCase().endsWith('.jpeg') ) ){
			urls.push(aLinks[el].getAttribute('href'));
		}
	}

	var imageContainer = document.createElement('div');
	imageContainer.classList.add('wikibase-statementgroupview');
	imageContainer.innerHTML = "";

	for (var url in urls){
		var img = document.createElement('img');
		img.style.width = "95%";
		img.style.height = "auto";
		img.style.marginTop="0.2em";
		img.style.marginBottom="0.2em";
		img.setAttribute('src',urls[url]);
		var a = document.createElement('a');
		a.setAttribute('href',urls[url]);
		a.setAttribute('target','_blank');
		a.appendChild(img);
		imageContainer.appendChild(a);

	}
	//imageContainer.style.border = "1px solid #c8ccd1"
	imageContainer.style.borderBottom = "none";
	imageContainer.style.marginBottom = 0;
	imageContainer.style.textAlign = 'center';
	imageContainer.style.width = '100%';
	imageContainer.style.backgroundColor = '#eaecf0';
	//document.querySelector(".wikibase-listview").insertBefore(imageContainer, p200Container);
    window.setTimeout(function(){
    p200Container.parentNode.insertBefore(imageContainer, p200Container);
},500)


}

// ---------------
if (document.querySelector("#P20")){

	var downloadBlockText = function(){

		var p20Container = document.querySelector("#P20")

		var aLinks = p20Container.querySelectorAll("a")
		
		var urls = []
		for (var i = 0; i < aLinks.length; i++) {


			if (aLinks[i].getAttribute('href') && aLinks[i].getAttribute('href').indexOf('semlab.s3.amazonaws.com/texts/') >-1){
				urls.push(aLinks[i].getAttribute('href'))
			}
		}

		var textContainer = document.createElement('div')
		textContainer.classList.add('wikibase-statementgroupview')
		textContainer.innerHTML = ""

		var request = new XMLHttpRequest();
		request.open('GET', urls[0], true);

		request.onload = function () {
		  if (this.status >= 200 && this.status < 400) {
		    // Success!
			document.querySelector("#P19").remove()
			var text = this.response
			var textBlock = document.createElement('pre')
			textBlock.style.marginBottom=0
			textBlock.innerText = text				
			textBlock.style.marginTop = 0
			textContainer.appendChild(textBlock)
			textContainer.style.marginBottom = 0
			textContainer.style.borderBottom = "none"				
            window.setTimeout(function(){
  			  document.querySelector(".wikibase-listview").insertBefore(textContainer, p20Container);
            },500);
		  } else {
		    // We reached our target server, but it returned an error
		  }
		};
		request.onerror = function () {
		  // There was a connection error of some sort
		};
		request.send();
	}
	downloadBlockText()
}

// ---------------------

if (document.querySelector("#P3")){	
	var instanceOf = []

	if (document.querySelector("#P1")){
		var els = document.querySelector("#P1").querySelectorAll("a")
		for (var i = 0; i < els.length; i++) {


			if (els[i].getAttribute('href') && (els[i].getAttribute('href').indexOf('wiki/Item') >-1 ) ){
				instanceOf.push(els[i].getAttribute('href').split(":")[1])
			}
		}
	}

	var P3Container = document.querySelector("#P3")

	var aLinks = P3Container.querySelectorAll("a")
	var urls = []

	for (var i = 0; i < aLinks.length; i++) {
		if (aLinks[i].getAttribute('href') && (aLinks[i].getAttribute('href').toLowerCase().endsWith('.png') || aLinks[i].getAttribute('href').toLowerCase().endsWith('.jpg') || aLinks[i].getAttribute('href').toLowerCase().endsWith('.jpeg') ) ){
			urls.push(aLinks[i].getAttribute('href'))
		}
	}
	if (urls.length>0){
		var thumbnailContainer = document.createElement('div')
		thumbnailContainer.style.width ='100%'
		thumbnailContainer.style.textAlign ='center'
		var thumbImg = document.createElement('img')
		thumbImg.setAttribute('src',urls[0])
		thumbImg.style.maxHeight = '250px'
		thumbImg.style.objectFit = 'contain'
        thumbImg.style.marginBottom = '2em'

		thumbImg.style.border = "1px solid #c8ccd1"

		if (instanceOf.indexOf('Q1')>-1){
			thumbImg.style.borderRadius = '15em'
		}
		thumbnailContainer.appendChild(thumbImg)

		var hr = document.createElement('hr')
		hr.style.marginTop = "0.5em"
		hr.style.marginBottom = "0.5em"
		// hr.style.backgroundColor = '#eaecf0'
		// thumbnailContainer.appendChild(hr)
		document.querySelector(".wikibase-entityview-side").appendChild(thumbnailContainer)

	}

}

// ---------------------


	var qid = document.querySelector('.wikibase-title-id').innerText.replace("(",'').replace(")",'')

	var buildInverse = function(){

		var inversePropertiesSPARQL = ''		
		inversePropertiesSPARQL = inversePropertiesSPARQL + 'select ?s ?sLabel ?p ?propLabel  WHERE{ '
		inversePropertiesSPARQL = inversePropertiesSPARQL + '	  ?s ?p wd:' + qid + '.'
		inversePropertiesSPARQL = inversePropertiesSPARQL + '	  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }'
		inversePropertiesSPARQL = inversePropertiesSPARQL + '	  FILTER (?p != <http://base.semlab.io/prop/direct/P22> && ?p != <http://base.semlab.io/prop/direct/P21> && ?p != <http://base.semlab.io/prop/direct/P23> )'
		inversePropertiesSPARQL = inversePropertiesSPARQL + '	  ?prop wikibase:directClaim ?p .'
		inversePropertiesSPARQL = inversePropertiesSPARQL + '	}'
 
		inversePropertiesSPARQL = encodeURIComponent(inversePropertiesSPARQL)

		// var req = await fetch(, {
		//   "headers": {
		//     "accept": "application/sparql-results+json",
		//   },
		//   "method": "GET",
		// });

		var request = new XMLHttpRequest();
		request.open('GET', 'https://query.semlab.io/proxy/wdqs/bigdata/namespace/wdq/sparql?query=' + inversePropertiesSPARQL, true);
		request.setRequestHeader("accept", "application/sparql-results+json");


		request.onload = function () {
		  if (this.status >= 200 && this.status < 400) {
		    // Success!
		    var data = JSON.parse(this.response);

			var parsedData = {}

			for (var i = 0; i < data.results.bindings.length; i++) {
				var stmt = data.results.bindings[i]
				var sKey = stmt.s.value
				if (!parsedData[sKey]){
					parsedData[sKey] = {
						name: stmt.sLabel.value,
						qid: stmt.s.value.split('/').slice(-1)[0],
						stmts: []
					}
				}
				parsedData[sKey].stmts.push(stmt)
			}

			if (Object.keys(parsedData).length>0){
				var inverseRelationShipsDiv = document.createElement('div')

				var titleInfo = document.createElement('div')
				titleInfo.innerHTML = "Inverse Relationships "
				titleInfo.style.fontWeight = 'bold'
				titleInfo.style.marginBottom = "0.75em"
				var info = document.createElement('a')
				info.innerText = "(?)"
				info.setAttribute('title','Click for explination')
				info.style.fontWeight= 'normal'
				info.addEventListener('click',function(){
					document.querySelector('#inverse-relationships-explain').style.display='block'

				})
				titleInfo.appendChild(info)


				var explain = document.createElement('div')
				explain.innerHTML = "Statements from other entities that<br>point to " + document.querySelector('.wikibase-title-label').innerText
				explain.style.fontStyle= 'italic'
				explain.style.marginBottom= '2em'

				explain.style.fontSize= '90%'
				explain.style.display= 'none'
				explain.setAttribute('id','inverse-relationships-explain')



				inverseRelationShipsDiv.appendChild(titleInfo)
				inverseRelationShipsDiv.appendChild(explain)


				for (var k in parsedData){

					var irEntitiy = document.createElement('div')
					// irEntitiy.style.backgroundColor= "#eaecf0"
					irEntitiy.style.borderBottom= "solid 1px #eaecf0"
					irEntitiy.style.paddingLeft = "2.5px"
					irEntitiy.style.fontSize = "90%"
					var irEntitiyA = document.createElement('a')
					irEntitiyA.innerText = parsedData[k].name
                    irEntitiyA.title = parsedData[k].name
                    if (parsedData[k].name.length > 30){
                      irEntitiyA.innerText = parsedData[k].name.substring(0,30) +'...'
                    }

					irEntitiyA.setAttribute('href','/wiki/Item:'+parsedData[k].qid)
					irEntitiyA.setAttribute('target','_blank')
					irEntitiy.appendChild(irEntitiyA)
					inverseRelationShipsDiv.appendChild(irEntitiy)


					for (var i = 0; i < parsedData[k].stmts.length; i++) {

						var s = parsedData[k].stmts[i]
						var irStmt = document.createElement('div')
						irStmt.style.fontSize = "80%"
						var irStmtA = document.createElement('a')
						irStmt.style.textAlign = "right"
						irStmtA.innerText = s.propLabel.value
						irStmtA.setAttribute('href','/wiki/Item:'+parsedData[k].qid+'#'+s.p.value.split('/').slice(-1)[0])
						irStmtA.setAttribute('target','_blank')

						irStmt.appendChild(irStmtA)

						inverseRelationShipsDiv.appendChild(irStmt)
					}
				}
				var hr = document.createElement('hr')
				hr.style.marginTop = "0.5em"
				hr.style.marginBottom = "0.5em"
				// inverseRelationShipsDiv.appendChild(hr)
				document.querySelector(".wikibase-entityview-side").appendChild(inverseRelationShipsDiv)
				buildMentions()
			}else{
              buildMentions()
            }

		  } else {
		    // We reached our target server, but it returned an error
		  }
		};

		request.onerror = function () {
		  // There was a connection error of some sort
		};

		request.send();



	}

	var buildMentions = function(){

		var mentionsSPARQL = ''
		mentionsSPARQL = mentionsSPARQL + 'select ?s ?doc ?docLabel ?localId  WHERE{   '
		mentionsSPARQL = mentionsSPARQL + '	  ?s wdt:P21 wd:' + qid + '.'
		mentionsSPARQL = mentionsSPARQL + '	  ?s wdt:P24 ?doc.'
		mentionsSPARQL = mentionsSPARQL + '	  ?s wdt:P17 ?localId. '
		mentionsSPARQL = mentionsSPARQL + '	  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }'
		mentionsSPARQL = mentionsSPARQL + '	}'
		
		mentionsSPARQL = encodeURIComponent(mentionsSPARQL)


		var request = new XMLHttpRequest();
		request.open('GET', 'https://query.semlab.io/proxy/wdqs/bigdata/namespace/wdq/sparql?query=' + mentionsSPARQL, true);
		request.setRequestHeader("accept", "application/sparql-results+json");


		request.onload = function () {
		  if (this.status >= 200 && this.status < 400) {
		    // Success!
		    var data = JSON.parse(this.response);

			var parsedData = {}


			for (var i = 0; i < data.results.bindings.length; i++) {
				var stmt = data.results.bindings[i]
				var sKey = stmt.doc.value
				if (!parsedData[sKey]){
					parsedData[sKey] = {
						name: stmt.docLabel.value,
						qid: sKey.split('/').slice(-1)[0],
						stmts: []
					}
				}
				parsedData[sKey].stmts.push(stmt)
			}


			if (Object.keys(parsedData).length>0){
				var mentionsDiv = document.createElement('div')

				var titleInfo = document.createElement('div')
				titleInfo.innerHTML = "Block Mentions "
				titleInfo.style.fontWeight = 'bold'
				titleInfo.style.marginBottom = "0.75em"
				var info = document.createElement('a')
				info.innerText = "(?)"
				info.setAttribute('title','Click for explination')
				info.style.fontWeight= 'normal'
				info.addEventListener('click',function(){
					document.querySelector('#mentions-explain').style.display='block'

				})
				titleInfo.appendChild(info)


				var explain = document.createElement('div')
				explain.innerHTML = "Blocks that have mentions<br>of " + document.querySelector('.wikibase-title-label').innerText
				explain.style.fontStyle= 'italic'
				explain.style.fontSize= '90%'
                explain.style.marginBottom= '2em'
				explain.style.display= 'none'
				explain.setAttribute('id','mentions-explain')



				mentionsDiv.appendChild(titleInfo)
				mentionsDiv.appendChild(explain)


				for (var k in parsedData){

					var irEntitiy = document.createElement('div')
					// irEntitiy.style.backgroundColor= "#eaecf0"
					irEntitiy.style.borderBottom= "solid 1px #eaecf0"
					irEntitiy.style.paddingLeft = "2.5px"
					irEntitiy.style.fontSize = "90%"
					var irEntitiyA = document.createElement('a')
					irEntitiyA.innerText = parsedData[k].name
                    irEntitiyA.title = parsedData[k].name
                    if (parsedData[k].name.length > 30){
                      irEntitiyA.innerText = parsedData[k].name.substring(0,30) +'...'
                    }
					irEntitiyA.setAttribute('href','/wiki/Item:'+parsedData[k].qid)
					irEntitiyA.setAttribute('target','_blank')
					irEntitiy.appendChild(irEntitiyA)
					mentionsDiv.appendChild(irEntitiy)
					var irStmt = document.createElement('div')
                    irStmt.style.textAlign = "right"
                    irStmt.style.fontSize = "80%"

					for (var i = 0; i < parsedData[k].stmts.length; i++) {
						var s = parsedData[k].stmts[i]
						
						var irStmtA = document.createElement('a')
						
						irStmtA.innerText = s.localId.value
						//irStmtA.style.paddingLeft = "0.5em"
                        irStmtA.style.display = "inline"
						irStmtA.setAttribute('href','/wiki/Item:'+s.s.value.split('/').slice(-1)[0])
						irStmtA.setAttribute('target','_blank')
                        
                        
						irStmt.appendChild(irStmtA)
                        var space = document.createElement('span')
                        space.innerText = " "
                        irStmt.appendChild(space)
                        if (irStmt.children.length>=10){
                          mentionsDiv.appendChild(irStmt)
                          var irStmt = document.createElement('div')
                          irStmt.style.textAlign = "right"
                          irStmt.style.fontSize = "80%"

                          
                        }


					}
                    mentionsDiv.appendChild(irStmt)	



				}
				var hr = document.createElement('hr')
				hr.style.marginTop = "0.5em"
				hr.style.marginBottom = "0.5em"
				// mentionsDiv.appendChild(hr)
				document.querySelector(".wikibase-entityview-side").appendChild(mentionsDiv)
			}








		  } else {
		    // We reached our target server, but it returned an error
		  }
		};

		request.onerror = function () {
		  // There was a connection error of some sort
		};

		request.send();



	}







	buildInverse()