MediaWiki:AddQuickClaim.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.
// <nowiki>

/*
  Quick helper script to add claim to a Wikidata item. 

  Author: [[User:Multichill]], based on [[MediaWiki:Catcheck.js]] by [[User:Lupo]]
  License: Quadruple licensed GFDL, GPL, LGPL and Creative Commons Attribution 3.0 (CC-BY-3.0)
  
  Choose whichever license of these you like best :-)
*/

/*jshint curly:false*/
/*global mw:false, $:false*/
mw.loader.using( ['mediawiki.api'], function() {

'use strict';

if (mw.config.get('wgNamespaceNumber') !== 0 || mw.config.get('wgAction') !== 'edit') {
  return;
}

window.AddQuickClaim =
{
  run : function ()
  {
  	var entityId = mw.config.get('wbEntityId');
  	var api = new mw.Api();
    // Grab the property and item id from the url
    var propertyIdUrl = window.location.href.match(/propertyid=(P\d+)&entityid=Q(\d+)/)[1];
    var entityIdUrl = window.location.href.match(/propertyid=(P\d+)&entityid=Q(\d+)/)[2];
    // TODO: Could lookup the property and the item to show it to the user.
    // I have to ask the user otherwise people could be tricked into doing edits
    var doedit = confirm("Are you sure you want to add " + propertyIdUrl + ":Q" + entityIdUrl + "?");
    // Build the url to return to when it edit was successful 
    var returnurl = "https://" + window.location.hostname + "/wiki/" + entityId;
    if (propertyIdUrl && entityIdUrl && doedit) {
    	// TODO: Check if the statement isn't already on the item.
    	// Build the edit to be send to the api
    	var payload = "{\"claims\":[{\"mainsnak\":{\"snaktype\":\"value\",\"property\":\"" + propertyIdUrl + "\",\"datavalue\":{\"raw\": \"Q" + entityIdUrl + "\",\"value\": {\"entity-type\": \"item\",\"numeric-id\": " + entityIdUrl + ",\"id\": \"Q" + entityIdUrl + "\"},\"type\": \"wikibase-entityid\"}},\"type\":\"statement\",\"rank\":\"normal\"}]}";
    	var summary = "Adding claim [[Property:" + propertyIdUrl + "]] -> [[Q" + entityIdUrl + "]] using [[MediaWiki:AddQuickClaim.js]]";
    	api.postWithEditToken({
    		action: 'wbeditentity',
    		id: entityId,
    		summary: summary,
    		data: payload
    }).done( function() {
    	mw.notify(mw.msg('Added the claim to the item'));
    	// Wait 3 seconds and reload the item.
    	setTimeout(function() {
    		window.location.assign(returnurl);
    	}, 2000); 
    }).fail( function() {
    	mw.notify(mw.msg('Failed to add the claim to the item'));
    });
    }
  }
};
window.AddQuickClaim.run();
});

// </nowiki>