Jump to content

User:Flatscan/rescueTag.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.
// test for article namespace
if (wgNamespaceNumber == 0) {

const rescueTag_regexpAfdm = new RegExp('\{\{Article for deletion/dated\\|page=[^|]*');
const rescueTag_regexpAfdmPrefixLength = 34;
const rescueTag_regexpRescue = new RegExp('\{\{\\s*[Rr]escue\\s*(\\|.*?)?\}\}');
const rescueTag_afdPrefix = "Wikipedia:Articles for deletion/";

var rescueTag_headerText;
var rescueTag_done = false;

function rescueTag_init() {
  if (!wfSupportsAjax()) {
    jsMsg('<span class="error">Your browser does not seem to support AJAX, which is required for the rescueTag script.</span>');
    return;
  } else if (rescueTag_done) {
    jsMsg('Rescue tag already applied. Try reloading the page.');
    return;
  }

  // load again, handle delay between page load and tab click
  rescueTag_headerText = rescueTag_getHeaderText(wgPageName);
  if (!rescueTag_test(rescueTag_headerText)) {
    jsMsg('Rescue tag is not appropriate – no {'+'{Article for deletion/dated}} found or {'+'{Rescue}} already placed. Try reloading the page.');
    return;
  }

  form = '<div id="rescueTag_initialform">'+
    '<h3>Rescue tag</h3>'+
    '<label for="rescueTag_reason">Tag rationale (optional):</label><input type="text" id="rescueTag_reason" name="rescueTag_reason" size=50 />'+
    '<input type="button" id="rescueTag_button_commit" name="rescueTag_button_commit" value="Add tag" onclick="rescueTag_commit()" /></div>';

  jsMsg(form);
}

function rescueTag_commit() {
  afdpage = rescueTag_regexpAfdm.exec(rescueTag_headerText)[0];
  afdpage = afdpage.substr(rescueTag_regexpAfdmPrefixLength);

  rescueTag_headerText = rescueTag_headerText.replace(
    "-->\n<!-- End of AfD message, feel free to edit beyond this point -->",
    "-->\n{"+"{Rescue|page="+afdpage+"}}\n<!-- End of AfD message, feel free to edit beyond this point -->"
  );

  esTag = '{'+'{Rescue}}';
  esNotification = '{'+'{[[Template:Afdrescue|Afdrescue]]}}';
  reason = document.getElementById('rescueTag_reason').value;
  if (reason.length == 0) {
    esTag += ', [['+rescueTag_afdPrefix+afdpage+']]';
  } else {
    esTag += ', ' + reason;
    esNotification += ', ' + reason;
  }

  token = rescueTag_getToken();
  rescueTag_commitEdit(wgPageName, token, esTag, '&notminor=1&section=0&text=' + encodeURIComponent(rescueTag_headerText));
  rescueTag_commitEdit(rescueTag_afdPrefix+afdpage, token, esNotification, '&notminor=1&appendtext=' + encodeURIComponent('{'+'{subst:Afdrescue}}'));

  rescueTag_done = true;
  jsMsg('Rescue tag applied and notification posted.');

  // force reload
  location.reload();
}

function rescueTag_test(headerText) {
  if (!rescueTag_regexpAfdm.test(headerText)) {
    return false;
  } else if (rescueTag_regexpRescue.test(headerText)) {
    return false;
  }
  return true;
}

function rescueTag_getHeaderText(pageName) {
  var req = sajax_init_object();
  req.open("GET", wgScriptPath + "/api.php?action=query&prop=revisions&rvprop=content&rvsection=0&format=json&indexpageids=1&titles="+encodeURIComponent(pageName), false);
  req.send(null);
  var response = eval('(' + req.responseText + ')');
  pageid = response['query']['pageids'][0];
  if (pageid == "-1") {
    delete req;
    return '';
  }
  pagetext = response['query']['pages'][pageid]['revisions'][0]['*'];
  delete req;
  return pagetext;
}

function rescueTag_getToken() {
  var req = sajax_init_object();
  req.open("GET", wgScriptPath + "/api.php?action=query&prop=info&indexpageids=1&intoken=edit&format=json&titles="+encodeURIComponent(mw.config.get('wgPageName')), false);
  req.send(null);
  var response = eval('(' + req.responseText + ')');
  pageid = response['query']['pageids'][0];
  token = response['query']['pages'][pageid]['edittoken'];
  delete req;
  return token;
}

function rescueTag_commitEdit(title, token, summary, textParams) {
  var req = sajax_init_object();
  var params = "action=edit&format=json&token="+encodeURIComponent(token)+"&title="+encodeURIComponent(title)+"&summary="+encodeURIComponent(summary)+textParams;
  url = wgScriptPath + "/api.php";
  req.open("POST", url, true);
  req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  req.setRequestHeader("Content-length", params.length);
  req.setRequestHeader("Connection", "close");
  req.onreadystatechange = function() {
    if(req.readyState == 4 && req.status == 200) {
      response = eval('(' + req.responseText + ')');
      try {
        if (response['edit']['result'] == "Success") {
          // success
        } else {
          alert('Failure on ' + title + '; Error info:' +response['error']['code'] + ' : ' + response['error']['info']);
        }
      }
      catch(err) {
        alert('Failure on ' + title + '; Unspecified error.');
      }
      delete req;
    }
  }
  req.send(params);
}

function rescueTag_testAndAddLink() {
  rescueTag_headerText = rescueTag_getHeaderText(wgPageName);
  if (rescueTag_test(rescueTag_headerText)) {
    mw.util.addPortletLink("p-cactions", "javascript:rescueTag_init()", "Rescue", "ca-rescue", "Rescue tag");
  }
}
 
$(rescueTag_testAndAddLink);
}