User:Jackmcbarn/editProtectedHelper.js#L-214

//

var browserHasDataCorruptionBug = $('

')[0].outerHTML != '
';

if(browserHasDataCorruptionBug && ('undefined' === typeof ephAllowDataCorruptionBug || !ephAllowDataCorruptionBug)) {

$(document).ready(function() {

$('.editrequest .mbox-text').append('The editProtectedHelper script is currently disabled because your browser has a bug which will cause corruption of pages that it edits with Parsoid. See here for details. To override this, add "ephAllowDataCorruptionBug = true;" immediately above the line where you load this script. You are responsible for any damage to pages that this causes.');

});

// only enable this on the latest revision of the page

} else if(mw.config.get('wgRevisionId') == mw.config.get('wgCurRevisionId')) {

$(document).ready(function() {

mw.loader.using( ['mediawiki.api'], function() {

'use strict';

var templateResponses = [

[ '', '(No template response)' ],

[ 'd', 'Done' ],

[ 'pd', 'Partly done:' ],

[ 'nd', 'Not done:' ],

[ 'nfn', 'Not done for now:' ],

[ 'c', 'Not done: please establish a consensus for this alteration before using the {{edit protected}} template.'] , // TODO make dynamic

[ 'rs', 'Not done: please provide reliable sources that support the change you want to be made.' ],

[ 'xy', 'Not done: it\'s not clear what changes you want made. Please mention the specific changes in a "change X to Y" format.' ],

[ 'mis', 'Not done: this is the talk page for discussing improvements to the template {{EP}}. Please make your request at the talk page for the article concerned.'], // TODO make dynamic

[ 'sb', 'Not done: please make your requested changes to the template\'s sandbox first; see WP:TESTCASES.' ],

[ 'tp', 'Not done: this is the talk page for discussing improvements to the template {{EP}}. If possible, please make your request at the talk page for the article concerned. If you cannot edit the article\'s talk page, you can instead make your request at Wikipedia:Requests for page protection#Current requests for edits to a protected page.' ],

[ 'a', 'Already done' ],

[ 'hr', 'Not done: According to the page\'s protection level and your user rights, you should be able to edit the page yourself. If you seem to be unable to, please reopen the request with further details.'],

[ 'nlp', 'Not done: The page\'s protection level has changed since this request was placed. You should now be able to edit the page yourself. If you still seem to be unable to, please reopen the request with further details.'],

[ 'doc', 'Not done: {{edit protected}} is usually not required for edits to the documentation, categories, or interlanguage links of templates using a documentation subpage. Use the \'edit\' link at the top of the green "Template documentation" box to edit the documentation subpage.' ],

[ 'drv', 'Not done: requests for recreating deleted pages protected against creation should be made at Wikipedia:Deletion review.' ],

[ 'r', 'Not done: requests for increases to the page protection level should be made at Wikipedia:Requests for page protection.' ],

[ 'ru', 'Not done: requests for decreases to the page protection level should be directed to the protecting admin or to Wikipedia:Requests for page protection if the protecting admin is not active or has declined the request.' ],

[ 'p', 'Not done: this is not the right page to request additional user rights. You may reopen this request with the specific changes to be made and someone will add them for you.'], // TODO make dynamic

[ 'm', 'Not done: page move requests should be made at Wikipedia:Requested moves.' ],

[ 'q', 'Question:' ],

[ 'note', 'Note:' ],

[ 'udp', 'Undone: This request (or the completed portion of it) has been undone.' ],

[ 'ud', 'Undone: This request has been undone.' ]

];

var selector = $('.editrequest .mbox-text');

// Global variable. In onParsoidDomReceived, this is set

// to the ETag header so that we can pass it back later

// in convertModifiedDom.

var gEtag;

// Global variable. In onParsoidDomReceived, this is

// set to the string we get back from the Parsoid API.

// Used in convertModifiedDom.

var parsoidDom;

var selectedLevel = { semi: [' selected="selected"', , , , ], extended: [, ' selected="selected"', , , ], template: [, , ' selected="selected"', , ], full: [, , , ' selected="selected"', ], interface: [, , , , ' selected="selected"'] };

var templateLevel = { semi: 'semi-', extended: 'extended-', template: 'template-', full: 'fully-', interface: 'interface-' };

var responseLevel = { semi: '{' + '{subst:ESp|', extended: '{' + '{subst:EEp|', template: '{' + '{subst:ETp|', full: '{' + '{subst:EP|', interface: '{' + '{subst:EIp|' };

var warnOnRespond = false, warnOnQuickRespond = true, warnOnRemove = true, autoFixLevel = true;

var quickResponses = [

[ 'd', '', 'Done'],

[ 'rs', '', 'Needs reliable sources'],

[ 'xy', '', 'Unclear/X to Y'],

[ 'hr', '', 'Could always edit'],

[ 'nlp', '', 'Can edit now'],

[ 'mis', '', 'Misplaced']

];

if('undefined' !== typeof ephWarnOnRespond) {

warnOnRespond = ephWarnOnRespond;

}

if('undefined' !== typeof ephWarnOnQuickRespond) {

warnOnQuickRespond = ephWarnOnQuickRespond;

}

if('undefined' !== typeof ephWarnOnRemove) {

warnOnRemove = ephWarnOnRemove;

}

if('undefined' !== typeof ephAutoFixLevel) {

autoFixLevel = ephAutoFixLevel;

}

if('undefined' !== typeof ephQuickResponses) {

quickResponses = ephQuickResponses;

}

function yesno(val, def) {

if(typeof val === 'string') {

val = val.toLowerCase();

}

if(typeof val === 'undefined' || val === '') {

return undefined;

} else if(val === 'yes' || val === 'y' || val === 'true' || val === 1) {

return true;

} else if(val === 'no' || val === 'n' || val === 'false' || val === 0) {

return false;

}

return def;

}

function getBanner(level, pagename, answered, force, demo) {

return '{{edit ' + templateLevel[level] + 'protected' + (pagename !== ? '|' + pagename : ) + '|answered=' + (answered ? 'yes' : 'no') + (force ? '|force=yes' : '') + (demo ? '|demo=yes}}' : '}}');

}

function getResponse(level, template, free) {

return ':' + (template === ? : responseLevel[level] + template + '}} ') + (free === ? : free + ' ') + '~~' + "~~\n";

}

function makeUniqueString(index) {

// this looks like a strip marker on purpose

return "\x7fUNIQ" + Math.random().toString(16).substr(2) + '-editProtectedHelper-' + index + "-QINU\x7f";

}

function saveWikitextFromParsoid(parsoidObj, data) {

var newWikitext, tmp, removerequest = false;

if(parsoidObj.removerequest) {

tmp = data.split(parsoidObj.templateMarker);

removerequest = true;

newWikitext = tmp[0];

if(parsoidObj.respondedInPage) {

tmp = tmp[1].split(parsoidObj.responseMarker);

newWikitext = newWikitext.replace(/\n+$/, ) + "\n\n" + tmp[1].replace(/^\n+/, );

}

} else {

var response = getResponse(parsoidObj.form.level.value, parsoidObj.form.responsetemplate.value, parsoidObj.form.responsefree.value);

var banner = getBanner(parsoidObj.form.level.value, parsoidObj.form.pagetoedit.value, parsoidObj.form.answered.checked, parsoidObj.form.force.checked, parsoidObj.demo);

// prevent empty response

if(response == ':~~' + "~~\n") {

response = '';

}

tmp = data.split(parsoidObj.templateMarker);

newWikitext = tmp[0].replace(/\n*$/, tmp[0].trim().length ? "\n\n" : '') + banner + tmp[1].replace(/^\n*/, "\n");

if(parsoidObj.respondedInPage) {

tmp = newWikitext.split(parsoidObj.responseMarker);

newWikitext = tmp[0].replace(/\n*$/, "\n") + response + tmp[1].replace(/^\n*/, "\n");

} else {

newWikitext = newWikitext.replace(/\n*$/, "\n") + response;

}

}

var resultObj = parsoidObj.resultObj, sectionName = parsoidObj.section && parsoidObj.section.text().trim();

if(sectionName && (sectionName.indexOf(parsoidObj.templateMarker) !== -1 || sectionName.indexOf(parsoidObj.responseMarker) !== -1)) {

// someone put an edit request template inside the section header, or something like that.

// don't even try to include a working section link in that case

sectionName = null;

}

//console.log(newWikitext);

resultObj.text('Saving...');

debugger; // triggers only if debugger is active

new mw.Api().get( { action: 'query', prop: 'revisions', rvprop: 'timestamp', revids: mw.config.get('wgRevisionId') }).done(function(data) {

new mw.Api().postWithEditToken( { action: 'edit', pageid: mw.config.get('wgArticleId'), text: newWikitext, summary: (sectionName ? '/' + '* ' + sectionName + ' *' + '/ ' : '') + (removerequest ? 'Removed' : 'Responded to') + ' edit request', tags: 'editProtectedHelper', notminor: true, nocreate: true, basetimestamp: data.query.pages[mw.config.get('wgArticleId')].revisions[0].timestamp } ).done(function(result) {

if(typeof(result.edit.newrevid) === 'undefined' || typeof(result.edit.oldrevid) === 'undefined') {

resultObj.css('color', 'red').text("Error: The API response omitted required information. Please check the page's history manually to see whether your edit was saved properly. The console may contain details.");

} else {

resultObj.css('color', 'green').text('Success: Loading diff...');

if( window.editProtectedHelperReloadAfter ) {

window.location.reload( /* forcedReload */ true );

} else {

location.href = mw.config.get('wgScript') + '?diff=' + result.edit.newrevid + '&oldid=' + result.edit.oldrevid;

}

}

}).fail(function(err) {

resultObj.css('color', 'red').text('Error: ' + err + '. The console may contain details.');

}).always(console.log);

});

}

function convertModifiedDom(e) {

var parsoidObj, nextRequestBeforeHeader = false;

if(warnOnRespond && !confirm('Are you sure you want to respond to this edit request?')) {

return false;

}

$('.editrequest button').prop('disabled', true);

parsoidObj = e.data;

parsoidObj.resultObj.text('Preparing new wikitext...');

var editReqTpl = $(parsoidObj);

// Don't break about continuity - get to the first

// element of the tranclusion block

while (editReqTpl && editReqTpl.attr('data-mw') === undefined) {

editReqTpl = editReqTpl.prev();

}

if (!editReqTpl) {

console.log("Error 3: Unexpected error traversing DOM. Cannot save!");

return;

}

var error = false;

editReqTpl.before(parsoidObj.templateMarker);

$('h1,h2,h3,h4,h5,h6,.editrequest', parsoidDom).each(function() {

var obj = $(this);

if(!obj.hasClass('editrequest')) {

// obj is a heading

if(obj.closest('[typeof="mw:Transclusion"]').length) {

// it's from a template transclusion. ignore

return true;

}

if(obj.add(parsoidObj)[0] === this) {

// (section) heading shows up before the edit request banner.

// Set as our section header (tentatively) and otherwise ignore.

parsoidObj.section = obj;

return true;

}

} else {

// obj is a (potentially different) edit request.

if(obj.add(parsoidObj)[0] === this) {

// not after our edit request banner. ignore

return true;

} else {

nextRequestBeforeHeader = true;

}

}

if (obj.attr('about')) {

// Don't break about continuity - get to the first

// element of the tranclusion block

while (obj && obj.attr('data-mw') === undefined) {

obj = obj.prev();

}

if (!obj) {

error = true; // Don't know what happened here!

return false;

}

}

obj.before(parsoidObj.responseMarker);

parsoidObj.respondedInPage = true;

return false;

});

if (error) {

console.log("Error 4: Unexpected error traversing DOM. Cannot save!");

return;

}

// If the section header is immediately before a request being removed, remove it too

// Do this before removing the edit req (template)

if(parsoidObj.removerequest && !nextRequestBeforeHeader && editReqTpl.prev().is(parsoidObj.section)) {

parsoidObj.section.remove();

}

// Remove the edit req (template)

$('[about="' + $(parsoidObj).attr('about').replace('\\', '\\\\').replace('"', '\\"') + '"]', parsoidDom).remove();

$.ajax({

type: 'POST',

url: '/api/rest_v1/transform/html/to/wikitext/' + encodeURIComponent(mw.config.get('wgPageName')) + '/' + mw.config.get('wgRevisionId'),

headers: {

Accept: 'text/plain; charset=utf-8; profile="mediawiki.org/specs/wikitext/1.0.0"',

'Api-User-Agent': 'editProtectedHelper (https://en.wikipedia.org/wiki/User:Jackmcbarn/editProtectedHelper)',

'If-Match': gEtag

},

data: { html: parsoidDom.documentElement.outerHTML },

success: function(data) { return saveWikitextFromParsoid(parsoidObj, data); }

});

}

function appendForm(obj, level, pagename, answered, force, parsoidObj) {

if(browserHasDataCorruptionBug) {

$(obj).append('

WARNING: Your browser has a bug which will cause corruption of pages that it edits with Parsoid. See here for details. You are responsible for any damage to pages that this causes.
');

}

var form = $('