User:Mattflaschen/CommonsHelper Labs.js

Note: After saving, you have to bypass your browser's cache to see the changes. Internet Explorer: press Ctrl-F5, Mozilla: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Opera/Konqueror: press F5, Safari: hold down Shift + Alt while clicking Reload, Chrome: hold down Shift while clicking Reload.
// CommonsHelper.  Originally written by Krimpet.
// Released into the public domain

// Rewritten by [[User:Superm401]]
// [[:Category:User scripts|Superm401's CommonsHelper]]

// Should be loaded remotely from a client site like English Wikipedia.
// E.g. http://en.wikipedia.org/wiki/User:Superm401/CommonsHelper_Labs.js (or the cross-loading function of your choice).

( function ( mw, $ ) {
	$( function () {
		var serverName = mw.config.get( 'wgServerName' ),
			SERVER_NAME_REGEX = /^([^.]+)\.([^.]+)\.org$/,
			serverNameMatch = serverName.match( SERVER_NAME_REGEX ),
			// serverLanguage is really just the part before the first dot
			serverLanguage = serverNameMatch ? serverNameMatch[1] : '',
			project = serverNameMatch ? serverNameMatch[2] : '',
			interfaceLanguage = mw.config.get( 'wgUserLanguage' ),
			encodedImageTitle = encodeURIComponent( mw.config.get( 'wgTitle' ) ),
			moveToCommonsLabelText = "Move file to Commons",
			moveToCommonsTitleText = "Begin moving this file to Commons",
			$wikiPreview = $( '#wikiPreview' ),
			$button,
			commonsHelperUrl = 'https://tools.wmflabs.org/commonshelper/?interface=' + 
					interfaceLanguage +
					'&image=' + encodedImageTitle +
					'&lang=' + serverLanguage +
					'&project=' + project;
			
		if ( mw.config.get( 'wgCanonicalNamespace' ) === 'File' ) {
			mw.loader.using( 'mediawiki.util', function () {
				mw.util.addPortletLink(
					'p-tb',
					commonsHelperUrl,
	   				moveToCommonsLabelText,
	   				't-movetocommons',
	   				moveToCommonsTitleText,
	   				null,
	   				// I want to put it under "Upload file", but I have to specify the *next* one, so this may not always work.
	   				// However, there's a fallback to just put it last.
	   				'#t-specialpages'
	   			);
			} );

			if ( $wikiPreview.length > 0 ) {
				$button = $( '<button>' ).attr( 'class', 'mw-ui-button mw-ui-progressive' )
					.text( moveToCommonsLabelText ).click( function () {
						window.location.href = commonsHelperUrl;
					});
				$( '#editform' ).before( $button );
			}
		}
	} );
}( mediaWiki, jQuery ) );