Jump to content

User:Þjarkur/Restorer.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
/*** Restorer ***/

// Easily restore an older version of a page
// Documentation at [[User:BrandonXLF/Restorer]]
// By [[User:BrandonXLF]]

$(function(){
	function restore (user, revid, userEditSummary) {
		var restorerSummary = window.restorerSummary || 'Reverted to revision $ID by [[Special:Contributions/$USER|$USER]]. $USER_EDIT_SUMMARY ([[User:BrandonXLF/Restorer|Restorer]])';
		$.post( mw.config.get('wgScriptPath') + '/api.php', {
			action: 'edit',
			pageid: mw.config.get('wgArticleId'),
			undo: mw.config.get('wgCurRevisionId'),
			undoafter: revid,
			summary: restorerSummary.replace(/\$ID/g, revid).replace(/\$USER_EDIT_SUMMARY/g, userEditSummary).replace(/\$USER/g, user),
			token: mw.user.tokens.get('csrfToken'),
			format: 'json'
		})
		.fail(function (a,b,c,d,e) {
			console.log(a,b,c,d,e);
			mw.notify('An error occured while restoring the revision.', {type:'error'});
		})
		.done(function (result) {
			console.log(result);
			if (result.error) {
				mw.notify(result.error.info, {type:'error'});
			} else {
				mw.notify('Restored revision sucessfully.');
				location.reload();
			}
		});
	}
	function addLink (item) {
		var revid = item.getAttribute('data-mw-revid'), user, links, ele, parent;
		if (revid != mw.config.get('wgCurRevisionId')) {
			user = item.getElementsByClassName('mw-userlink')[0].textContent.replace('User:','');
			links = item.getElementsByClassName('mw-changeslist-links');
			links = links[links.length - 1];
			parent = document.createElement('span');
			ele = document.createElement('a');
			ele.addEventListener('click', function() {
				var userEditSummary = prompt("Explanation for edit (optional):", "");
				if(userEditSummary !== null) {
					restore(user, revid, userEditSummary);
				}
			});
			ele.innerHTML = 'restore';
			parent.appendChild(ele);
			links.appendChild(parent);
		}
	}
	(function () {
		if (location.search.includes('action=history')) {
			var i, parents = document.querySelectorAll('li[data-mw-revid]');
			console.log(parents);
			for (i = 0; i < parents.length; i++) {
				addLink(parents[i]);
			}
		}
	})();
});