MediaWiki:ExCommons.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.
/**
* @description exCommons - copy files to individual Wikis before deleting them on Commons
* @author (c) 2014 Magnus Manske
* @license released under GPL v2+
* <nowiki>
*/
/*global jQuery, mediaWiki*/
/*jshint multistr:true*/
( function( $, mw ) {
'use strict';
var conf = mw.config.get(['wgAction', 'wgNamespaceNumber', 'wgPageName', 'wgTitle']);

var exCOM = {

	sites: {},
	no_local_upload: ['es.wikipedia.org'],
	auto_check: ['en.wikipedia.org'],
	empty: true,
	oauth: 'https://magnustools.toolforge.org/oauth_uploader.php?callback=?',
	authorized: false,

	init: function () {
		if (conf.wgNamespaceNumber !== 6 || // not a file
			conf.wgAction !== 'delete' // not deleting
		) return;

		var h = "<div id='ex_commons'><div id='ex_commons_oauth' style='float:right'><i>Checking OAuth...</i></div><div id='ex_commons_main'><i>Finding global usage of this file...</i></div></div>";
		$('#mw-content-text').prepend(h);
		this.checkOAuth();
		this.checkGlobalUsage();
	},

	checkGlobalUsage: function (continuation) {
		var self = this;
		var params = {
			action: 'query',
			prop: 'globalusage',
			gulimit: 500,
			gufilterlocal: 1,
			guprop: 'namespace',
			format: 'json',
			titles: conf.wgPageName
		};
		if (continuation)
			$.extend(params, continuation);
		$.post('/w/api.php', params, function (d) {
			$.each(((d.query || {}).pages || {}), function (file_page_id, v) {
				$.each((v.globalusage || []), function (k2, v2) {
					self.empty = false;
					if (!v2.ns) {
						self.sites[v2.wiki] = true; // NS 0
					} else {
						if (!self.sites[v2.wiki])
							self.sites[v2.wiki] = false; // Other namespace
					}
				});
			});

			if (d['continue']) {
				self.checkGlobalUsage(d['continue']);
				return;
			}

			self.showResults();
		}, 'json');
	},

	showResults: function () {
		if (this.empty)
			return $('#ex_commons_main').html("This file is not used in any other project.");
		
		var self = this;
		var h = "<h3>This file is used on other Wikimedia projects</h3>\
			<div><i>Note:</i> It appears that you need to be an admin on the target wiki itself to upload a file if the same name exists on Commons. Fix will be supplied over the weekend.</div>\
			<div style='-moz-column-count:2;-webkit-column-count:2;column-count:2;-moz-column-gap: 1em;-webkit-column-gap: 1em;column-gap: 1em;'>";
		$.each(this.sites, function (site, has_ns0) {
			var text,
				siteEscaped = mw.html.escape(site || '');

			if (has_ns0)
				text = "<b title='The site uses this file in an article'>" + siteEscaped + "</b>";
			else
				text = "<span title='Does not use this file in an article'>" + siteEscaped + "</span>";

			h += "<div site='" + siteEscaped + "' class='ex_commons_site'>";
			if (-1 !== $.inArray(site, self.no_local_upload)) {
				h += "<input type='checkbox' disabled />&nbsp;<s>" + text + "</s> <i>no local upload available</i>";
			} else {
				h += "<label><input type='checkbox' class='ex_commons_cb' site='" + siteEscaped + "' ";
				if (has_ns0 && -1 !== $.inArray(site, self.auto_check))
					h += " checked";
				h += " />&nbsp;" + text + "</label>";
			}
			h += " <span class='ex_commons_result' site='" + siteEscaped + "'></span></div>";
		});
		h += "</div>";
		h += "<input type='button' id='ex_commons_run' value='Copy file to selected wikis' />";

		// Get file description
		$.get('/w/api.php', {
			action: 'parse',
			page: conf.wgPageName,
			format: 'json',
			prop: 'wikitext'
		}, function (d) {
			self.desc = ( d && d.parse && d.parse.wikitext && d.parse.wikitext['*'] ) || '';
			self.desc = self.desc.replace(/\{\{delete.+?\}\}/i, '');
			self.desc = "{{From Commons}}\n\n" + self.desc;
			$('#ex_commons_main').html(h);
			$('#ex_commons_run').click(self.run);
		}, 'json');
	},

	run: function () {
		var self = exCOM;
		if (!self.authorized)
			return alert("OAuth is required for this to work. Please click on the link on the right and authorize, then reload this page.");
		var targets = [];
		$('#ex_commons_main input:checked').each(function () {
			targets.push($(this).attr('site'));
		});

		var running = targets.length;
		if (!running)
			return alert("No wikis selected!");

		$.get('/w/api.php', {
			action: 'query',
			titles: conf.wgPageName,
			prop: 'imageinfo',
			format: 'json',
			iiprop: 'url'
		}, function (d0) {
			var url;
			$.each((d0.query.pages || {}), function (pageid, v) {
				url = v.imageinfo[0].url;
			});
			if (!url)
				return alert("Can not find URL for this file; deleted already?");

			$.each(targets, function (dummy, site) {
				$.getJSON(self.oauth, {
					action: 'upload',
					site: site,
					url: url,
					newfile: conf.wgTitle,
					desc: self.desc,
					ignorewarnings: 1,
					comment: 'File is about to be deleted on Commons, evacuating to individual wikis',
					botmode: 1
				}, function (d) {
					var o = $('span.ex_commons_result[site="' + site + '"]');

					console.log(d);
					if (d.error === 'OK') {
						o.html("<span style='color:green'>OK</span>");
					} else {
						o.html("<span style='color:red'>" + d.res.error.info + "</span>");
					}

					running--;
					if (!running)
						self.finish();
					//console.log ( d ) ;
				});
			});
		}, 'json');

	},

	finish: function () {
		// TODO
	},

	checkOAuth: function () {
		var self = this;
		$.getJSON(self.oauth, {
			action: 'checkauth',
			botmode: 1
		}, function (d) {
			if (d.error === 'OK') {
				$('#ex_commons_oauth').html("OAuth OK!");
				self.authorized = true;
			} else {
				$('#ex_commons_oauth').html("<a target='_blank' href='https://magnustools.toolforge.org/oauth_uploader.php?action=authorize'><b>Log into OAuth!</b></a>");
			}
		});
	},

	fin: ''
};

$(function () {
	exCOM.init();
});
}(jQuery, mediaWiki));
// </nowiki>