User:Ricordisamoa/FopThreat.js

From Meta, a Wikimedia project coordination wiki

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.
/* <nowiki>
 *
 * FopThreat.js
 * @author [[User:Ricordisamoa]]
 *
 * Blackens files threatened by the 2015 EU Copyright Reform
*/
/* global $, mw */
mw.loader.using( [ 'mediawiki.RegExp', 'mediawiki.Title', 'mediawiki.Uri' ] ).done( function () {
	mw.hook( 'wikipage.content' ).add( function ( $content ) {
		var uploadBase = '//upload.wikimedia.org/wikipedia/commons',

		files = {},

		getPageTitle = function ( href ) {
			try {
				href = new mw.Uri( href );
			} catch ( e ) {
				return;
			}

			if ( href.query.hasOwnProperty( 'title' ) ) {
				return href.query.title;
			} else {
				var titleRegex = new RegExp( mw.RegExp.escape( mw.config.get( 'wgArticlePath' ) )
					.replace( '\\$1', '(.+)' ) ),
				matches = titleRegex.exec( href.path );
				return matches ? decodeURIComponent( matches[1] ) : undefined;
			}
		},

		getFileTitle = function ( href ) {
			var title = getPageTitle( href );
			if ( !title ) {
				return;
			}
			title = mw.Title.newFromUserInput( title );
			if ( title.namespace === 6 ) {
				return title.title + '.' + title.ext;
			}
		};

		$content.find( 'a.image' ).each( function () {
			var
				title,
				$this = $( this ),
				$img = $( this ).find( 'img' );

			if ( $img.attr( 'src' ).substring( 0, uploadBase.length ) === uploadBase ) {
				title = getFileTitle( $this.attr( 'href' ) );
				if ( title ) {
					if ( files[title] === undefined ) {
						files[title] = [];
					}
					files[title].push( [ $this, $img ] );
				}
			}
		} );

		$.get( '//tools.wmflabs.org/ricordisamoa/fop.php', { files: Object.keys( files ) } )
		.done( function ( data ) {
			$.each( data.files || [], function ( i, file ) {
				$.each( files[file] || [], function ( x, linkAndImg ) {
					linkAndImg[1].removeAttr( 'src' )
						.removeAttr( 'srcset' )
						.removeAttr( 'alt' )
						.css( 'background', 'black' )
						.click( function ( event ) {
							// kill MediaViewer
							event.stopPropagation();
						} );

					linkAndImg[0].attr( 'title', 'Click here to know why this image was blackened' )
						.attr( 'href', '//meta.wikimedia.org/wiki/Freedom_of_Panorama_in_Europe_in_2015' );
				} );
			} );
		} );
	} );
} );