User:Aude/authority.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.
/* AuthorityControl.js
 * Provides a link to various Authority Control tools (VIAF, GND, etc.) for Wikidata statements that
 * feature certain properties.
 *
 * Original gadget coded by [[User:Ricordisamoa]]
 */
( function ( mw, wb, $ ) {
'use strict';

if ( ( mw.config.get( 'wgNamespaceNumber' ) !== 0 && mw.config.get( 'wgNamespaceNumber' ) !== 120 ) || !mw.config.exists( 'wbEntityId' ) ) {
	// Only item pages feature appropriate statements.
	return;
}

var PROPERTIES = {},
	specialHandlingProperties = [
		'P426', // aircraft registration
		'P791', // ISIL ID
		'P839', // IMSLP ID
		'P882', // FIPS
		'P1362', // Theaterlexikon der Schweiz online ID
		'P1793' // Format as a regular expression
	];

/*
*/
function getGeoHackParams( coord ) {
	// TODO: individual scale for every precision

	var globes = {
		Q2: 'earth',
		Q111: 'mars',
		Q308: 'mercury',
		Q313: 'venus',
		Q319: 'jupiter',
		Q339: 'pluto',
		Q405: 'moon',
		Q596: 'ceres',
		Q2565: 'titan',
		Q3030: 'vesta',
		Q3123: 'io',
		Q3134: 'callisto',
		Q3143: 'europa',
		Q3169: 'ganymede',
		Q3303: 'enceladus',
		Q3322: 'titania',
		Q3332: 'oberon',
		Q3338: 'umbriel',
		Q3343: 'ariel',
		Q3352: 'miranda',
		Q3359: 'triton',
		Q7547: 'phobos',
		Q7548: 'deimos',
		Q15034: 'mimas',
		Q15037: 'hyperion',
		Q15040: 'dione',
		Q15047: 'tethys',
		Q15050: 'rhea',
		Q16711: 'eros',
		Q17958: 'iapetus',
		Q17975: 'phoebe',
		Q107556: 'lutetia',
		Q158244: 'gaspra'
	};

	var globeQKey = coord.globe.replace( 'http://www.wikidata.org/entity/', '' );
	var globe = globes[ globeQKey ];

	return coord.latitude + '_N_' + coord.longitude + '_E_globe:' + globe;
}

/**
 * Get the snak value formatted with a link.
 *
 * @param {number} numericPropertyId Refers to PROPERTIES.
 * @param {string} value
 */
function getLinkValueForString( numericPropertyId, value ) {
	var linkValue;

	switch ( Number( numericPropertyId ) ) {
		case 839:
		case 1362:
			linkValue = value.replace( / /g, '_' );
			break;
		case 882: // FIPS
			linkValue = value;
			linkValue = linkValue.substr( 0, 2 ) + '/' + linkValue;
			break;
		case 1793: // Format as a regular expression
			linkValue = value.replace( /\+/g, '%2b' );
			break;
		default:
			linkValue = value;
	}

	return linkValue;
}

function makeLink( numericPropertyId, linkValue, displayText ) {
	var linkTemplate = PROPERTIES[ numericPropertyId ];

	switch ( Number( numericPropertyId ) ) {
		case 426:
			if ( linkValue.substring( 0, 1 ) === 'N' ) {
				linkTemplate = 'http://registry.faa.gov/aircraftinquiry/NNum_Results.aspx?NNumbertxt=$1';
			} else if ( linkValue.substring( 0, 2 ) === 'G-' ) {
				linkTemplate = 'https://www.caa.co.uk/application.aspx?catid=60&pagetype=65&appid=1&mode=detailnosummary&fullregmark=$1';
				linkValue = linkValue.substring( 2 );
			} else {
				return linkValue;
			}
			break;
		case 791:
			if ( linkValue.substring( 0, 3 ) === 'DE-' ) {
				linkTemplate = 'http://dispatch.opac.d-nb.de/DB=1.2/CMD?ACT=SRCHA&IKT=8529&TRM=$1';
			} else {
				return linkValue;
			}
			break;
		default:
			linkTemplate = PROPERTIES[ numericPropertyId ];
	}

	return $( '<a>' )
		.text( displayText )
		.attr( 'href', linkTemplate.replace( /\$1/g, linkValue ) )
		// Show the 'external link' icon:
		.addClass( 'external' );
}

function createLinkForString( numericPropertyId, value ) {
	var linkValue = getLinkValueForString( numericPropertyId, value );
	return makeLink( numericPropertyId, linkValue, value );
}

function createLinkForSnakValue( numericPropertyId, dataValue, displayText ) {
	var dataValueType = dataValue.getType(),
		value = dataValue.toJSON();

	// @fixme shouldn't happen but in case of any unexpected data value types,
	// then there should be better error handling here.
	var linkValue = '';

	if ( dataValueType === 'string' ) {
		linkValue = getLinkValueForString( numericPropertyId, value );
	} else if ( dataValueType === 'globecoordinate' ) {
		linkValue = getGeoHackParams( value );
	}

	return makeLink( numericPropertyId, linkValue, displayText );
}

function linkSnakView( el, propertySelector, valueSelector ) {
	var $propLink = $( el ).find( propertySelector );

	var title = $propLink.attr( 'title' );

	if ( title ) {
		var titleParts = title.split( ':P' ),
			numericPropertyId = titleParts[ 1 ];

		if ( PROPERTIES.hasOwnProperty( numericPropertyId ) ) {
			var $value = $( el ).find( valueSelector ).first(),
				$link = createLinkForString( numericPropertyId, $value.text() );

			$value.html( $link );
		}
	}
}

function handleSnak( snak, snakView ) {
	if ( !( snak instanceof wikibase.datamodel.PropertyValueSnak ) ) {
		return;
	}

	var numericPropertyId = snak.getPropertyId().slice( 1 );
	if ( !( PROPERTIES.hasOwnProperty( numericPropertyId ) ) ) {
		return;
	}
	var $snakValue = $( snakView ).find( '.wikibase-snakview-value' ),
		displayText = extractDisplayText( $snakValue ),
		snakLink = createLinkForSnakValue( numericPropertyId, snak.getValue(), displayText );
		
	$snakValue.html( snakLink );
}

function extractDisplayText( $snakValue ) {
	var $snakValueClone = $snakValue.clone();
		
	$snakValueClone.children().remove();
		
	return $snakValueClone.text();
}

/**
 * Initializes the gadget.
 * This procedure needs to be performed as good as possible. jQuery selector usage should be limited
 * to a minimum.
 */
function initGadget() {
	if ( $.isEmptyObject( PROPERTIES ) ) {
		return;
	}

	$( ':wikibase-statementview' ).each( function () {
		var statementview = $.data( this, 'statementview' ),
			statement = statementview.value(),
			claim = statement.getClaim(),
			qualifierGroups = claim.getQualifiers().getGroupedSnakLists();

		handleSnak( claim.getMainSnak(), statementview.$mainSnak[0] );

		$( '.wikibase-statementview-qualifiers .wikibase-snaklistview', this ).each( function( i ) {
			var qualifiers = qualifierGroups[i].toArray();
			$( '.wikibase-snakview', this ).each( function( n ) {
				handleSnak( qualifiers[n], this );
			} );
		} );

	} );

	$( '.wikibase-referenceview .wikibase-snaklistview-listview' ).each( function () {
		linkSnakView( this, '.wikibase-snakview-property > a', '.wikibase-snakview-value' );
	} );
}

function getProperties() {
	var api = new mw.Api(),
		repoApi = new wb.api.RepoApi( api ),
		prop,
		propertyIds = [],
		alreadyLinkedPropertyIds = [],
		entity = JSON.parse( mw.config.get( 'wbEntity' ) );

	function addSnak( snak ) {
		var snakPropertyId = snak.property;

		if ( snak.snaktype !== 'value' ||
			( snak.datavalue.type !== 'string' && snak.datavalue.type !== 'globecoordinate' ) ) {
			return;
		}
		if ( propertyIds.indexOf( snakPropertyId ) !== -1 ) {
			return;
		}
		if ( specialHandlingProperties.indexOf( snakPropertyId ) === -1 ) {
			if ( alreadyLinkedPropertyIds.indexOf( snakPropertyId ) !== -1 ) {
				return;
			}
			if ( $( '#' + snakPropertyId ).find( '.wikibase-snakview-variation-valuesnak:first > a' ).length > 0 ) {
				alreadyLinkedPropertyIds.push( snakPropertyId );
				return;
			}
		}

		propertyIds.push( snakPropertyId );
	}

	for ( prop in entity.claims ) {
		$.each( entity.claims[ prop ], function ( i, claim ) {
			addSnak( claim.mainsnak );
			$.each( claim.references || [], function ( i, ref ) {
				for ( prop in ref.snaks ) {
					$.each( ref.snaks[ prop ], function ( i, cl ) {
						addSnak( cl );
					} );
				}
			} );
			for ( prop in claim.qualifiers || {} ) {
				$.each( claim.qualifiers[ prop ], function ( i, cl ) {
					addSnak( cl );
				} );
			}
		} );
	}
	if ( !propertyIds.length ) {
		return $.Deferred().resolve();
	}
	return repoApi.getEntities( propertyIds, 'claims' )
	.done( function ( data ) {
		$.each( data.entities, function ( entityId, entity ) {
			if ( entity.datatype === "external-id" && $.inArray( entity.id, specialHandlingProperties ) === -1 ) {
				// No need to format these
				return true;
			}
			$.each( entity.claims, function ( claimId, claim ) {
				if ( claimId === 'P1630' ) {
					PROPERTIES[ entityId.slice( 1 ) ] = claim[ 0 ].mainsnak.datavalue.value;
				}
			} );
		} );
	} );
}

getProperties().done( function () {
	$( initGadget );
} );

}( mediaWiki, wikibase, jQuery ) );