Jump to content

User:K6ka/fakerollback.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.
/* <nowiki>
 * Rollback.js by [[User:Ricordisamoa]]
 * --------------------experimental--------------------
 * provides the 'rollback' link to non-rollbackers
 * THIS SOFTWARE IS PROVIDED "AS IS", YOU OWN ANY RESPONSIBILITY WHILE USING IT
 * !!! not intended for use by vandals !!!
*/
$(document).ready(function(){
	var undoLink=$('ul#pagehistory li:first-child span.mw-history-undo');
	var ntitle=$('#mw-diff-ntitle2');
	if(undoLink.length===0&&(ntitle.length===0||$('#differences-nextlink').length>0)&&['Contributions','Watchlist','Recentchanges','Recentchangeslinked'].indexOf(mw.config.get('wgCanonicalSpecialPageName'))==-1) return;// no [rollback] button to insert
	// TODO: auto-patrol reverted changes
	if(mw.config.get('wgUserGroups').indexOf('rollbacker')!=-1||mw.config.get('wgUserGroups').indexOf('sysop')!=-1) return;// user is rollbacker, no need for these buttons
	var modules=['jquery.jStorage'];
	var diffOnRb=(mw.user.options.get('norollbackdiff')!=1);
	if(diffOnRb) modules.push('mediawiki.action.history.diff');
	var botMode=mw.util.getParamValue('bot');
	mw.loader.using(modules,function(){
		var api=new mw.Api();
		api.get(
			{
				action:'query',
				meta:'allmessages',
				amlang:mw.config.get('wgUserLanguage'),
				ammessages:'rollback-success|rollbacklink|rollbacklinkcount|rollbacklinkcount-morethan|action-rollback|tooltip-rollback|cantrollback|actioncomplete|rollbackfailed|returnto'
			}
		)
		.done(function(data){
			var createRbLink=function(pageTitle,lastEditor){
				if($.jStorage.get('fake_rollback-action')==='done'){
					$.jStorage.deleteKey('fake_rollback-action');
					$.jStorage.deleteKey('fake_rollback-summary');
					jsMsg($.jStorage.get('fake_rollback-success'));
					$.jStorage.deleteKey('fake_rollback-success');
				}
				else if($.jStorage.get('fake_rollback-action')==='todo'&&$('#wpSummary').length===1&&mw.config.get('wgAction')==='edit'&&mw.util.getParamValue('restore')!=null){
					$.jStorage.set('fake_rollback-action','done');
					$('#wpSummary').val($.jStorage.get('fake_rollback-summary'));
				}
				var messages={};
				$.each(data.query.allmessages,function(i,e){
					messages[e.name]=e['*'];
					if(e['*'].indexOf('{{PLURAL')!=-1){
						var s=e['*'].match(/^(.*)\{\{PLURAL: ?\$1\|([^\|]*)(\|([^\|]*))?\}\}(.*)$/).slice(1);
						s.splice(2,1);
						if(typeof s[2]=='undefined') s[2]='';
						messages[e.name]=s;
					}
				});
				var rbLink;
				api.get(
					{// get the latest 11 editors
						action:'query',
						prop:'revisions',
						rvlimit:11,
						titles:pageTitle,
						rvprop:'user'
					},
					{async:false}
				)
				.done(function(data){
					if(typeof data.query=='undefined') return null;
					var page=data.query.pages[Object.keys(data.query.pages)[0]];
					var rbEdits=null;
					$.each(page.revisions,function(i,rev){
						if(rev.user.replace(/ /g,'_')!=lastEditor.replace(/ /g,'_')){
							rbEdits=i;
							return false;
						}
					});
					var pmsg=function(c,x){
						return ($.isArray(messages[c])?(messages[c][0]+messages[c][(x===1?1:2)]+messages[c][3]):messages[c]).replace(/\$1/g,x);
					};
					var rbLinkText=messages.rollbacklink;
					if(rbEdits==null){
						if(page.revisions.length==11) rbLinkText=pmsg('rollbacklinkcount-morethan',10);
						else return null;
					}
					else rbLinkText=pmsg('rollbacklinkcount',rbEdits);
					var rbLinkHrefConfig={
						title:pageTitle,
						action:'rollback',
						user:lastEditor,
						token:mw.user.tokens.get('csrfToken')
					};
					if(botMode!=null) rbLinkHrefConfig['bot']=botMode;
					rbLink=$('<a>')
					.attr({
						href:mw.util.wikiScript()+'?'+$.param(rbLinkHrefConfig),
						title:messages['tooltip-rollback']
					})
					.text(rbLinkText)
					.click(function(event){
						event.preventDefault();
						var rbl=this;
						api.get(
							{// require the username, the revId and the content
							//  of the last revision not made by the last user
								action:'query',
								prop:'revisions',
								rvlimit:1,
								titles:pageTitle,
								rvexcludeuser:lastEditor,
								rvprop:'timestamp|user|content|ids',
								meta:'allmessages',
								amlang:mw.config.get('wgContentLanguage'),
								ammessages:'revertpage'
							}
						)
						.done(function(data){
							$.each(data.query.allmessages,function(i,e){
								messages[e.name]=e['*'];
							});
							var page=data.query.pages[Object.keys(data.query.pages)[0]];
							if(typeof page.revisions=='undefined'||page.revisions.length===0){
								window.history.pushState({path:window.location.href},'',rbl.href);
								$('#firstHeading').text(messages.rollbackfailed);// the last editor of the page is its single one
								$('#p-views ul>li').removeClass('selected');
								$('#contentSub').empty();
								$('#mw-content-text').text(messages.cantrollback);
								return;
							}
							var revision=page.revisions[0];
							var rbSummary=messages.revertpage.replace(/\$1/g,revision.user).replace(/\$2/g,lastEditor);
							var rbSuccess=messages['rollback-success'].replace(/\$2/g,revision.user).replace(/\$1/g,lastEditor);
							if(mw.config.get('wbEntityType')!=null){
								$.jStorage.set('fake_rollback-summary',rbSummary);
								$.jStorage.set('fake_rollback-success',rbSuccess);
								$.jStorage.set('fake_rollback-action','todo');
								window.location.href=mw.util.getUrl(pageTitle)+'?action=edit&restore='+revision.revid;
							}
							else{
								var rbContent=revision['*'];
								var rbPostConfig={
									action:'edit',
									text:rbContent,
									//undo:$('#pagehistory li:first-child .mw-history-undo a').attr('href').match(/undo=([0-9]+)($|[^0-9])/)[1],
									restore:revision.revid,
									title:pageTitle,
									summary:rbSummary,
									minor:1,
									token:mw.user.tokens.get('csrfToken')
								};
								if(botMode!=null) rbPostConfig['bot']=botMode;
								api.post(rbPostConfig)
								.done(function(data){
									window.history.pushState({path:window.location.href},'',rbl.href);
									$('#p-views ul>li').removeClass('selected');
									$('#contentSub').empty();
									if(data&&data.error&&data.error.info){
										$('#firstHeading').text(messages.rollbackfailed);
										$('#mw-content-text').text(data.error.info);
									}
									else{
										$('#firstHeading').text(messages.actioncomplete);
										$('#mw-content-text').empty().append(
											$('<p>').text(rbSuccess)
										)
										.append(
											$('<p>').attr('id','mw-returnto').html(
												messages.returnto.replace(/\$1/g,
												'<a href="'+mw.util.getUrl(pageTitle)+
												'" title="'+pageTitle.replace(/_/g,' ')+'">'+
												pageTitle.replace(/_/g,' ')+'</a>')
											)
										);
										if(diffOnRb){
											api.get({
												action:'query',
												prop:'revisions',
												titles:pageTitle,
												rvdiffto:'prev',
												rvlimit:1
											}).done(function(rev){
												$('#mw-content-text').append(
													'<table class="diff">'+Array(3).join('<col class="diff-marker"/><col class="diff-content"/>')+
													rev.query.pages[Object.keys(rev.query.pages)[0]].revisions[0].diff['*']+'</table>'
												);
											});
										}
									}
								})
								.fail(function(){
									$('#firstHeading').text(messages.rollbackfailed);
									$('#mw-content-text').empty();
								});
							}
						});
					})
					.appendTo($('<span>').addClass('mw-rollback-link')).parent();
				});
				return rbLink;
			};
			if($('ul#pagehistory').length>0){
				var lastEditor=$('ul#pagehistory li:first-child span.history-user a.mw-userlink').first().text();
				var rbLink=createRbLink(mw.config.get('wgPageName'),lastEditor);
				if(typeof rbLink!='undefined') rbLink.insertBefore(undoLink).after(' | ');
			}
			else if(ntitle.length>0){
				var lastEditor=$('#mw-diff-ntitle2 a.mw-userlink').first().text();
				var rbLink=createRbLink(mw.config.get('wgPageName'),lastEditor);
				if(typeof rbLink!='undefined') rbLink.prepend('[').append(']').appendTo(ntitle).before('&nbsp;&nbsp;&nbsp;');
			}
			else if(mw.config.get('wgCanonicalSpecialPageName')=='Contributions'){
				var lastEditor=mw.util.getParamValue('target');
				if(lastEditor===null) lastEditor=mw.config.get('wgPageName').split('/')[1];
				$('.ns-special ul li').each(function(i,e){
					var uctop=$(e).find('.mw-uctop');
					if(uctop.length==1&&$(e).find('.newpage').length==0){// only top edits, excluding new pages
						var rbLink=createRbLink($(e).find('.mw-contributions-title').text(),lastEditor);
						if(typeof rbLink!='undefined') rbLink.prepend(' [').append(']').insertAfter(uctop);
					}
				});
			}
			else if(['Watchlist','Recentchanges','Recentchangeslinked'].indexOf(mw.config.get('wgCanonicalSpecialPageName'))!=-1){
				$('.ns-special ul li').each(function(i,e){
					var rbLink=createRbLink($(e).find('.mw-changeslist-title').text(),$(e).find('.mw-userlink').text());
					if(typeof rbLink!='undefined') rbLink.prepend(' [').append(']').appendTo(e);
				});
			}
		});
	});
});
// </nowiki>