User:Terasail/Edit Request Tool.js: Difference between revisions

Content deleted Content added
Don't run on COI requests
Account for Template:Sudo
 
(37 intermediate revisions by 2 users not shown)
Line 1:
//*<nowiki>
Edit Request Tool
/*jshint esversion: 6*/
Created by: Terasail
function postEdit(wikitext, editSummary, pageName, secIndx) {
*/
let api = new mw.Api();
var dataERT;
api.postWithEditToken({
var userSignauteERT = "";
action: 'edit',
var editRequestBoxes = $('.editrequest');
title: pageName,
var editRequests = [];
text: wikitext,
for (let i = 0; i < editRequestBoxes.length; i++) {
section: secIndx,
if (typeof(editRequestBoxes[i].attributes['data-origlevel']) != 'undefined') {
summary: editSummary
if (editRequestBoxes[i].id == "") {
}).done(function(result) {
$(editRequestBoxes[i].children[0].children[0].children[0]).append('<div class="response-cell-ert" style="text-align:center;"></div>');
let encodePageName = encodeURIComponent(pageName);
} else {
window.___location = "/w/index.php?title=" + encodePageName + "&type=revision&diff=cur&oldid=prev";
$(editRequestBoxes[i].children[0]).append('<tr><td colspan="2" class="response-cell-ert" style="text-align:center;"></td></tr>');
}
editRequests.push(editRequestBoxes[i]);
}
}
 
if (editRequests.length > 0) {
mw.loader.using(["oojs-ui-core", "oojs-ui-widgets", "oojs-ui-windows"]).done(function() {
mw.loader.load(["oojs-ui.styles.icons-interactions", "oojs-ui.styles.icons-moderation", "oojs-ui.styles.icons-user", "oojs-ui.styles.icons-content", "oojs-ui.styles.icons-editing-core", "oojs-ui.styles.icons-editing-advanced"]);
loadERTool();
$.getJSON("https://en.wikipedia.org/w/index.php?title=User:Terasail/Edit_Request_Tool.json&action=raw&ctype=text/json", function (newData) {
dataERT = newData;
});
ApiGetERT({
action: "parse",
title: mw.config.get("wgPageName"),
text: "~~~~",
pst: "true",
disablelimitreport: "true",
disableeditsection: "true",
preview: "true"
}).then(function(data){
userSignauteERT = data.parse.text["*"].replaceAll(/([^]+(?=<p>)<p>|<\/div>)/g, " ");
});
});
}
 
async function loadERTool() {
function execute(responseTable, dataERT, replyOption, inputText, answered, boxType, targets) {//currentBox
// Get page watchers, visitors and user watch status.
OO.ui.confirm("Confirm in order to reply to this edit request.").done(function(confirmed) {
let watchStatus = [];
if (confirmed) {
let watchQuery = await ApiGetERT({
//Create label box & remove action buttons
action: "query",
let firstRow = responseTable.children[1].children[0];
prop: "info",
firstRow.innerHTML = "";
pageids: mw.config.get("wgArticleId"),
responseTable.children[5].children[0].remove();
inprop: "watchers|visitingwatchers|watched",
let infoBox = new OO.ui.MessageWidget( {
format: "json"
icon: 'pageSettings',
type: 'notice',
label: 'Processing request — Edit request starting, getting section data to edit.'
});
infoBox.$element[0].style = "margin:5px 0; max-width:50em";
$(firstRow).append(infoBox.$element);
//Create loading bar
let progressBar = new OO.ui.ProgressBarWidget( {
progress: false
});
$(firstRow).append(progressBar.$element);
//Set preview for output
if (replyOption[0] != "") {//Don't preview a non-response
showOutput(inputText, replyOption, responseTable.children[4].children[0], dataERT, boxType);
}
//Find header
let header = "";
let curElement = responseTable.parentNode;
do {
curElement = curElement.previousElementSibling;
if (curElement.getElementsByClassName("mw-headline").length == 1) {
header = curElement.getElementsByClassName("mw-headline")[0].id;
}
}
while (header == "");
let pageName = mw.config.values.wgPageName;
let api = new mw.Api();
api.get( {
action: "parse",
page: pageName,
prop: "sections|wikitext|revid"
}).done(function(data) {
infoBox.setLabel("Processing request — Making changes to the edit request");
let editTemplate = "{{Edit " + boxType + "-protected";
if (answered) { answered = "yes"; } else { answered = "no"; }
for (let c3 = 0; c3 < targets.length; c3++) {
editTemplate += "|" + targets[c3];
}
editTemplate += "|answered=" + answered;
let wikitext = data.parse.wikitext["*"];
let sections = data.parse.sections;
sections[sections.length] = {byteoffset: wikitext.length};//Add last value to be pagelength
let newRev = data.parse.revid;
let secIndx = sections[0], endIndx = sections[1];
for (let j = 0; j < sections.length - 1; j++) {//Run for all except last value
let tempSec = sections[j];
if (tempSec.anchor == header && !isNaN(Number(tempSec.index))) {
secIndx = tempSec;
endIndx = sections[j + 1];
} else if (tempSec.number.slice(0, secIndx.number.length) == secIndx.number) { //Get any subsections
endIndx = sections[j + 1];
}
}
wikitext = wikitext.slice(secIndx.byteoffset, endIndx.byteoffset);
wikitext = wikitext.slice(wikitext.indexOf("=="));
wikitext = wikitext.replace(/{{ *([SETFI]PER|Edit([ -]?[A-Z]+[ -]?| )Protected)\s*[^}}]*/i, editTemplate);
let editSummary = "/* " + header.replaceAll("_", " ") + " */ " + replyOption[2] + " ([[User:Terasail/Edit_Request_Tool|Edit Request Tool]])";
if (replyOption[1] != "Close") {
let lastMsg = wikitext.lastIndexOf("\n", wikitext.lastIndexOf("(UTC)")) + 1;
wikitext = wikitext.trim() + "\n:";
while(lastMsg == wikitext.indexOf(":", lastMsg)) {
lastMsg++;
wikitext += ":";
}
if (replyOption[0] != "") { wikitext += "{{subst:" + dataERT.protections[boxType][1] + replyOption[0] + "}} "; }
if (inputText != "") { wikitext += inputText.replaceAll(/\s*~~~~\s*/g, "") + " "; }
wikitext += "~~~~";
if (replyOption[1] == "Remove") {
wikitext = "";
editSummary = editSummary.replace(/[^]+\*\/ /, "");
}
}
infoBox.setType("success");
infoBox.setLabel("Processing request — Saving changes to the talk page.");
secIndx = parseInt(secIndx.index);
if (newRev == mw.config.values.wgRevisionId) {
postEdit(wikitext, editSummary, pageName, secIndx);
} else {
OO.ui.confirm("There has been a new revision to the page, do you wish to continue?").done(function(revCon) {
if (revCon) { postEdit(wikitext, editSummary, pageName, secIndx); }
});
}
});
}
});
let watchData = watchQuery.query.pages[mw.config.get("wgArticleId")];
let watched = watchData.watched;
let expiry = watchData.watchlistexpiry;
if (expiry) {
watched = Math.ceil((new Date(expiry).getTime() - Date.now()) / 1000 / 60 / 60 / 24) + " days";
}
watchStatus.push(watchData.watchers || "less than 30", watchData.visitingwatchers || "<30", watched);
//Increment through all edit requests & add respond button
for (let i = 0; i < editRequests.length; i++) {
let responseCell = $('.response-cell-ert')[i];
let smallButton = false;
if (responseCell.tagName == "DIV") {
smallButton = true;
}
let respondButton = new OO.ui.ButtonWidget({
icon: "edit",
label: "Respond",
flags: "progressive",
title: "Open the response menu for this request",
invisibleLabel: smallButton,
}).on("click", function() {
loadERTResponse(editRequests[i], respondButton, watchStatus);
respondButton.setDisabled(true);
});
respondButton.$element[0].style = "margin:5px";
$(responseCell).append(respondButton.$element);
}
}
 
function addButtonsloadERTResponse(currentBoxeditRequest, dataERTrespondButton, replyButtonwatchStatus) {
let boxType = currentBox.parentElementeditRequest.dataset.origlevel;
boxType = boxType.replace("full", "fully");
let tableElem = currentBox.parentElement;
$('<table style="border:1px solid #A2A9B1; border-radius:2px; padding:12px10px 16px 0; margin:auto; max-width:55em; width:100%; clear:both;"><tr><td><div style="colorfont-style:#808080italic; margin-left:1em;">There are currently ' + watchStatus[0] + ' users watching this page (' + watchStatus[1] + ' have viewed recent edits).</div><div>Quick options:</div></td></tr><tr style="display: flex; justify-content: center;"><td class="response-quick"></td></tr><tr><td style="color:#808080">Custom response:</td></tr><tr style="text-align:center;"><td class="response-custom"></td></tr><tr style="background:#F6F6F6;"><td class="response-preview" style="display:none;"><div style="color:#808080">Preview:</div><div></div></td></tr><tr style="margin-top:5px; display: flex; justify-content: right;"><td class="response-controls"></td></tr></table>').insertAfter(tableElemeditRequest);
let responseTableresponseBox = tableElemeditRequest.nextElementSibling.children[0];
let firstRowresponseQuick = responseTable$(responseBox).children[1]find('.childrenresponse-quick')[0];
let responseCustom = $(responseBox).find('.response-custom')[0];
let secondRow = responseTable.children[3].children[0];
let responsePreview = $(responseBox).find('.response-preview')[0];
let thirdRow = responseTable.children[4].children[0];
let responseControls = $(responseBox).find('.response-controls')[0];
let fourthRow = responseTable.children[5].children[0];
let protections = Object.entries(dataERT.protections);
let responses = Object.entries(dataERT.response);
Line 128 ⟶ 96:
tcOptions.push({data: protections[i][0], label: protections[i][1][0]});
}
let typeChange = new OO.ui.DropdownInputWidget( {
value: boxType,
options: tcOptions
});
typeChange.on("change", function () {
submitB.setDisabled(false);
});
typeChange.$element[0].style = "text-align:left; margin:auto";
$(secondRowresponseCustom).append(typeChange.$element);
//Create target page list
let boxLinks = currentBoxeditRequest.getElementsByClassName("mbox-text")[0].getElementsByClassName("external text");
let pageLinkspageTargets = [];
if (boxLinks.length > 0) {//Open request
for (let c1 = 0; c1 < boxLinks.length; c1++) {
if (boxLinks[c1].parentElement.tagName == "LI" || boxLinks[c1].parentElement.tagName == "B") {
pageLinkspageTargets[pageLinkspageTargets.length] = boxLinks[c1].innerHTML;
}
}
} else {//Closed request
boxLinks = currentBoxeditRequest.getElementsByClassName("mbox-text")[0].getElementsByTagName("A");
for (let c2 = 1; c2 < boxLinks.length; c2++) {
pageLinkspageTargets[pageLinkspageTargets.length] = boxLinks[c2].title;
}
if (pageLinkspageTargets.length == 0) {
pageLinkspageTargets = mw.config.values.get("wgPageName").replace(/(_talk|Talk:)/, "").replaceAll("_", " ");
}
}
let targetPages = new OO.ui.TagMultiselectWidget( {
placeholder: 'Target Pages',
allowArbitrary: true,
selected: pageLinkspageTargets
});
targetPages.on("change", function () {
submitB.setDisabled(false);
});
targetPages.$element[0].style = "text-align:left; margin:5px auto";
$(secondRowresponseCustom).append(targetPages.$element);
//Create dropdown menu
let dropMenu = new OO.ui.DropdownWidget( {
label: "Select reply option - Add additional text below",
menu: {items: []}
Line 173 ⟶ 147:
responses = dataERT.response;
dropMenu.$element[0].style = "text-align:left; margin:0px";
$(secondRowresponseCustom).append(dropMenu.$element);
dropMenu.on("labelChange", function () {
submitB.setDisabled(false);
showOutput(inputText, responses[dropMenu.getLabel()], thirdRow, dataERT, typeChange.value);
previewERT(inputText, responses[dropMenu.getLabel()], responsePreview, typeChange.value);
});
//Create input box
let inputText = new OO.ui.MultilineTextInputWidget({autosize: true, rows: 4, label: "Additional text"});
inputText.$element[0].style = "margin:5px auto";
$(secondRowresponseCustom).append(inputText.$element);
inputText.on("change", function (newText) {
showOutputpreviewERT(inputText, responses[dropMenu.getLabel()], thirdRow, dataERTresponsePreview, typeChange.value);
});
//Create top horizontal layout
Line 188 ⟶ 163:
//Create firstrow fieldset
let fieldsetT = new OO.ui.FieldsetLayout();
fieldsetT.addItems([new OO.ui.FieldLayout(new OO.ui.Widget({content: [hzLayoutT]}), {align: 'top'})]);
$(firstRowresponseQuick).append(fieldsetT.$element);
//Remove button
let remove = new OO.ui.ButtonWidget( {
icon: "trash",
flags: ["primary", "destructive"],
invisibleLabel: true,
title: "DeleteRemove entirethe section!"
});
remove.on("click", function () {
$(responseBox).find("tr").each(function(_, row) {
execute(responseTable, dataERT, nonResponses.Remove, "", null, typeChange.defaultValue, targetPages.getValue());
if ($(row).find('.response-quick').length == 0) {
row.remove();
}
});
hzLayoutT.clearItems();
//Create deletion options
let remSec = new OO.ui.ButtonWidget({//RemoveSection
icon: "trash",
flags: ["primary", "destructive"],
label: "Remove section",
title: "Remove the entire section!"
});
remSec.on("click", function () {
saveResponseERT([editRequest, responseQuick, responsePreview, responseControls], nonResponses.Remove, "", null, typeChange.defaultValue, targetPages.getValue(), "nochange", "");
});
hzLayoutT.addItems([remSec]);
hzLayoutT.addItems([cancelB]);
});
hzLayoutT.addItems([remove]);
//Open & Close button
if (currentBox.parentElementeditRequest.attributes[2].localName != "data-origlevel") {
let closeB = new OO.ui.ButtonWidget( {
icon: "unFlag",
invisibleLabel: true,
title: "Mark as answered"
});
closeB.on("click", function () {
executesaveResponseERT(responseTable[editRequest, dataERTresponseQuick, responsePreview, responseControls], nonResponses.Close, "", true, typeChange.defaultValue, targetPages.getValue(), "nochange", "");
});
hzLayoutT.addItems([closeB]);
} else {
let openB = new OO.ui.ButtonWidget( {
icon: "flag",
invisibleLabel: true,
title: "Mark as unanswered"
});
openB.on("click", function () {
executesaveResponseERT(responseTable[editRequest, dataERTresponseQuick, responsePreview, responseControls], nonResponses.Open, "", false, typeChange.defaultValue, targetPages.getValue(), "nochange", "");
});
hzLayoutT.addItems([openB]);
Line 230 ⟶ 222:
title: quickResponses[i][1][2]
});
newButton.on("click", function () {
executesaveResponseERT(responseTable[editRequest, dataERTresponseQuick, responsePreview, responseControls], responses[quickResponses[i][0]], "", toggleAns.selected, typeChange.defaultValue, targetPages.getValue(), "nochange", "");
});
hzLayoutT.addItems([newButton]);
Line 238 ⟶ 230:
let toggleAns = new OO.ui.CheckboxInputWidget({selected: true});
hzLayoutT.addItems([toggleAns, new OO.ui.LabelWidget({label: "Answered"})]);
//Create lastrow horizontal layout
let hzLayoutB = new OO.ui.HorizontalLayout();
//Create lastrow fieldset
let fieldsetB = new OO.ui.FieldsetLayout();
fieldsetB.addItems([new OO.ui.FieldLayout(new OO.ui.Widget({content: [hzLayoutB]}), {align: 'top'})]);
$(responseControls).append(fieldsetB.$element);
//Cancel response button
let cancelB = new OO.ui.ButtonWidget( {
icon: "cancel",
flags: ["destructive"],
Line 246 ⟶ 244:
title: "Cancel the response & close menu"
});
cancelB.on("click", function () {
replyButtonrespondButton.setDisabled(false);
responseTable.parentElementresponseBox.remove();
});
$(fourthRow)hzLayoutB.appendaddItems([cancelB.$element]);
//Watchlist dropdown
let watchOptions = [{data: "infinite", label: "Permanent"}, {data: "1 day", label: "1 day"}, {data: "3 days", label: "3 days"}, {data: "1 week", label: "1 week"}, {data: "1 month", label: "1 month"}];
let watchValue = "infinite";
if (!!watchStatus[2]) {
watchOptions.unshift({data: "nochange", label: watchStatus[2]});
watchValue = "nochange";
}
let watchlistLayout = new OO.ui.HorizontalLayout();
let watchlistDropdown = new OO.ui.DropdownInputWidget({
value: watchValue,
options: watchOptions,
disabled: (watchStatus[2] == undefined)
});
watchlistLayout.addItems([watchlistDropdown]);
//Watchlist checkbox & label
let watchlistCheckbox = new OO.ui.CheckboxInputWidget({
selected: (watchStatus[2] != undefined)
}).on("change", function (newStatus) {
watchlistDropdown.setDisabled(!newStatus);
});
let watchlistLabel = new OO.ui.LabelWidget({label: "Watch this page"}).on("change", function (newStatus) {
 
});
hzLayoutB.addItems([watchlistCheckbox, watchlistLabel, watchlistLayout]);
//Submit response button
let submitB = new OO.ui.ButtonWidget( {
icon: "checkAll",
flags: ["primary", "progressive"],
label: "Submit",
title: "Submit the response",
disabled: true
});
submitB.on("click", function () {
let newResponse = responses[dropMenu.getLabel()];
let newText = inputText.value;
if (typeof(newResponse) == "undefined") {
let isAns = toggleAns.selected;
newText = "";
let newType = typeChange.value;
newResponse = nonResponses.ChangeLevel; //Assume that it is a template change
let newTargets = targetPages.getValue();
let targetsnewPageTargets = targetPages.items[];
targetPages.items.forEach(function(item) {
let targetChange = false;
newPageTargets.push(item.label);
if (typeof(newResponse) != "undefined") {
});
execute(responseTable, dataERT, newResponse, newText, isAns, newType, newTargets);
if (pageTargets.toString() != newPageTargets.toString()) { //Check if the page targets were changed instead
} else if (typeChange.value != typeChange.defaultValue) {
execute(responseTable, newResponse dataERT,= nonResponses.ChangeLevel, "", isAns, newType, newTargets)ChangeTarget;
}
if (targets.length == pageLinks.length) {
for(let item = 0; item < targets.length; item++) {
if (targets[item].data != pageLinks[item]) { targetChange = true; }
}
} else {
targetChange = true;
}
if (targetChange) {
execute(responseTable, dataERT, nonResponses.ChangeTarget, "", isAns, newType, newTargets);
}
saveResponseERT([editRequest, responseQuick, responsePreview, responseControls], newResponse, newText, toggleAns.selected, typeChange.value, targetPages.getValue(), watchlistCheckbox.selected, watchlistDropdown.value);
});
$(fourthRow)hzLayoutB.appendaddItems([submitB.$element]);
}
 
function showOutputpreviewERT(inputText, replyOption, tableRow, dataERT, template) {
var restTransform = "https://en.wikipedia.org/api/rest_v1/transform/wikitext/to/html/" + encodeURIComponent(mw.config.get('wgPageName'));
let preview = ""inputText.value;
let newText = inputText.value;
if (typeof(inputText) == 'string') {
newText = inputText;
}
template = dataERT.protections[template][1];
if (typeof (replyOption) != "undefined") {
preview += "{{" + template + replyOption[0] + "}} " + preview;
}
if (newText != "" && typeof(newText) != "undefined") { preview += newText + " "; }
if (preview != "") {
preview = preview.replaceAll(/{{subst:/gi, "{{");
let nickname = " " + mw.user.options.values.nickname;
$.post(restTransform, 'wikitext=' + encodeURIComponent(preview) + '&body_only=true',
if (nickname == " ") {//Create default signature if no nickname
function (html) {
nickname = mw.user.getName();
if (inputText.value != "" || typeof (replyOption) != "undefined") {//Stops preview appearing with empty input box
nickname = " [[User:" + nickname + "|" + nickname + "]] ([[User talk:" + nickname + "|talk]])";
tableRow.style = "padding:8px 1em 2px;";
}
tableRow.children[1].innerHTML = html.replace("</p>", userSignauteERT);
let timeNow = new Date();
timeNow = timeNow.toLocaleDateString('en-GB', { year: 'numeric', month: 'long', day: 'numeric', hour:'2-digit', minute: '2-digit'}).split(" at ");
preview += nickname + " " + timeNow[1] + ", " + timeNow[0] + " (UTC)";
$.post(restTransform, 'wikitext=' + preview + '&body_only=true',
function(html) {
if (inputText.value != "" || typeof(replyOption) != "undefined") {//Stops preview appearing with empty input box
tableRow.style = "padding:8px 1em; 2px";
tableRow.children[1].innerHTML = html;
}
}
Line 319 ⟶ 322:
}
 
async function saveResponseERT(requestBox, responseOption, responseText, answered, requestType, targets, watchPage, watchValue) {
var editRequestBoxes = document.getElementsByClassName("plainlinks tmbox tmbox-notice editrequest");
await new Promise(function(resolve) {
if (editRequestBoxes.length != 0) {
OO.ui.confirm("Confirm in order to reply to this edit request.").done(function(confirmed) { if (confirmed) {
var jsonERTURL = "https://en.wikipedia.org/w/index.php?title=User:Terasail/Edit_Request_Tool.json&action=raw&ctype=text/json";
resolve();
$.getJSON(jsonERTURL, function(dataERT) {
} else {
mw.loader.using(["oojs-ui-core", "oojs-ui-widgets", "oojs-ui-windows"]).done(function() {
return;
mw.loader.load(["oojs-ui.styles.icons-layout", "oojs-ui.styles.icons-alerts", "oojs-ui.styles.icons-interactions", "oojs-ui.styles.icons-moderation", "oojs-ui.styles.icons-user", "oojs-ui.styles.icons-content", "oojs-ui.styles.icons-editing-core", "oojs-ui.styles.icons-editing-advanced"]);
}});
for (let i = 0; i < editRequestBoxes.length; i++) {
});
let currentBox = editRequestBoxes[i].children[0]; //The tbody tag for the box
//Create label box & remove action buttons
if (typeof(currentBox.parentElement.dataset.origlevel) != "undefined") {
requestBox[1].innerHTML = "";
let isSmall = false;
requestBox[3].remove();
if (editRequestBoxes[i].id == "") {
let infoBox = new OO.ui.MessageWidget({
isSmall = true;
icon: 'pageSettings',
}
type: 'notice',
let replyButton = new OO.ui.ButtonWidget( {
label: 'Processing request — Edit request starting, getting section data to edit.'
icon: "recentChanges",
});
flags: ["progressive"],
infoBox.$element[0].style = "margin:5px 0; max-width:50em";
label: "Respond",
$(requestBox[1]).append(infoBox.$element);
invisibleLabel: isSmall,
//Create loading bar
title: "Respond to the edit request."
let progressBar = new OO.ui.ProgressBarWidget({
});
progress: false
replyButton.on("click", function() {
});
addButtons(currentBox, dataERT, replyButton);
$(requestBox[1]).append(progressBar.$element);
replyButton.setDisabled(true);
//Set preview for output
});
if (responseOption[0] != "") {//Don't preview a non-response
replyButton.$element[0].style = "margin:2px 0";
let tempValue = {value:responseText};
if (isSmall) {
previewERT(tempValue, responseOption, requestBox[2], requestType);
$(currentBox.children[0].children[0]).append(replyButton.$element);
}
} else {
//Find header
$(currentBox).append('<tr><td colspan=2><div style="display: flex; justify-content: center;"></div></td></tr>');
let header = "";
$(currentBox.children[1].children[0].children[0]).append(replyButton.$element);
let sectionIndex = 0;
let tempElement = requestBox[0];
let sectionQuery = await ApiGetERT({
action: "parse",
page: mw.config.get("wgPageName"),
prop: "sections"
});
let sections = sectionQuery.parse.sections;
do {
tempElement = tempElement.previousElementSibling;
if (tempElement.classList.contains("mw-heading")) {
if (tempElement.parentElement.tagName == "SECTION") { //Need to support both while new parser is being implemented
header = $(tempElement).find("h1,h2,h3,h4,h5,h6")[0].id;
sectionIndex = parseInt(tempElement.parentElement.dataset.mwSectionId);
} else {
if (tempElement.getElementsByClassName("mw-headline").length > 0) { //Vector 2022
header = tempElement.getElementsByClassName("mw-headline")[0].id;
} else { //Vector Legacy
header = $(tempElement).find("h1,h2,h3,h4,h5,h6")[0].id;
}
for (let i = 0; i < sections.length; i++) {
if (sections[i].anchor == header) {
sectionIndex = parseInt(sections[i].index);
}
}
}
}
}
while (header == "");
infoBox.setLabel("Processing request — Making changes to the edit request");
let editSummary = "/* " + header.replaceAll("_", " ") + " */ " + responseOption[2] + " ([[User:Terasail/Edit_Request_Tool|Edit Request Tool]])";
let wikitextQuery = await ApiGetERT({
action: "parse",
page: mw.config.get("wgPageName"),
section: sectionIndex,
prop: "wikitext|revid"
});
let wikitext = wikitextQuery.parse.wikitext["*"];
let latestRevision = wikitextQuery.parse.revid;
if (responseOption[1] != "Remove") {
let editTemplate = "{{Edit " + requestType + "-protected";
for (let c3 = 0; c3 < targets.length; c3++) {
editTemplate += "|" + targets[c3];
}
if (answered) {
editTemplate += "|answered=yes";
} else {
editTemplate += "|answered=no";
}
wikitext = wikitext.replace(/{{ *([SETFI]PER|Edit([ -]?[A-Z]+[ -]?|[- ])Protected|Sudo)\s*[^}}]*/i, editTemplate);
if (responseOption[1] != "Close") {
wikitext = wikitext.trim() + "\n:";
if (responseOption[0] != "") {
wikitext += "{{subst:" + dataERT.protections[requestType][1] + responseOption[0] + "}} ";
}
if (responseText != "") {
wikitext += responseText.replaceAll(/\s*~~~~\s*/g, "") + " ";
}
wikitext += "~~~~";
}
} else {
wikitext = "";
editSummary = editSummary.replace(/[^]+\*\/ /, "");
}
infoBox.setType("success");
infoBox.setLabel("Processing request — Saving changes to the talk page.");
if (latestRevision != mw.config.values.wgRevisionId) {
await new Promise(function(resolve) {
OO.ui.confirm("There has been a new revision to the page, do you wish to continue?").done(function(confirmed) { if (confirmed) {
resolve();
} else {
return;
}});
});
}
if (watchPage) {
if (watchPage != "nochange") {
watchPage = "watch";
}
} else {
watchPage = "unwatch";
}
let apiParams = {
action: 'edit',
title: mw.config.get("wgPageName"),
text: wikitext,
section: sectionIndex,
summary: editSummary,
watchlist: watchPage
};
if (watchPage == "watch") {
apiParams.watchlistexpiry = watchValue;
}
new mw.Api().postWithEditToken(apiParams).done(function () {
window.___location = "/w/index.php?title=" + encodeURI(mw.config.get("wgPageName")) + "&type=revision&diff=cur&oldid=prev";
});
}
 
function ApiGetERT(params) {
return new Promise(function(resolve) {
new mw.Api().get(params)
.done(function (data) {resolve(data);})
.fail(function (data) {console.error(data);});
});
}