Snippets/Direct imagelinks to Commons

From MediaWiki.org
Jump to navigation Jump to search
How to use SnippetsSnippets
List of SnippetsCategory:All snippets
Crystal Clear action run.png
Direct imagelinks to Commons
Language(s): JavaScriptCategory:Snippets with JavaScript
Compatible with: MediaWiki 1.26+ 

Description[edit]

With this option you can transparently include Wikimedia Commons media files (images) as if they are stored on the local server. Images not found on the local server are automatically loaded from Wikimedia Commons. Actually the external images are cached on your server (load-through). Supports HTTPS.

Via LocalSettings.php[edit]

Since MediaWiki 1.16 it might be sufficient just to set the following flag in LocalSettings.php

$wgUseInstantCommons = true;

You might need to configure also the following variables when your host is behind a firewall/proxy:

$wgHTTPProxy = "myproxy.mycomp.net:8080";

Code[edit]

/**
 * Direct imagelinks to Commons
 *
 * Required modules: mediawiki.RegExp, mediawiki.util
 *
 * @source https://www.mediawiki.org/wiki/Snippets/Direct_imagelinks_to_Commons
 * @author Krinkle
 * @version 2017-08-30
 */
if ( mw.config.get( 'wgNamespaceNumber', 0 ) >= 0 ) {
	mw.loader.using( [ 'mediawiki.RegExp', 'mediawiki.util' ] ).then( function () {
		mw.hook( 'wikipage.content' ).add( function ( $content ) {
			var uploadBaseRe = /^(https:)?\/\/upload\.wikimedia\.org\/wikipedia\/commons/,
				localFileNSString = mw.config.get( 'wgFormattedNamespaces' )['6'] + ':',
				localBasePath = new RegExp( '^' + mw.RegExp.escape( mw.util.getUrl( localFileNSString ) ) ),
				localBaseScript = new RegExp( '^' + mw.RegExp.escape(
					mw.util.wikiScript() + '?title=' + mw.util.wikiUrlencode( localFileNSString )
				) ),
				commonsBasePath = 'https://commons.wikimedia.org/wiki/File:',
				commonsBaseScript = 'https://commons.wikimedia.org/w/index.php?title=File:';

			$content.find( 'a.image' ).attr( 'href', function ( i, currVal ) {
				if ( uploadBaseRe.test( $( this ).find( 'img' ).attr( 'src' ) ) ) {
					return currVal
						.replace( localBasePath, commonsBasePath )
						.replace( localBaseScript, commonsBaseScript );
				}
			} );
		} );
	} );
}

Notes[edit]

As of December 2012, installed as gadget (enabled by default) at:

In January 2014, it was also installed at:

On January 19th, 2014, it was installed also at:

It is furthermore included in the following files:

As of July 7th, 2015, it's also in many more places: phab:P896.

See also[edit]