User:Dudemanfellabra/AddCommonsCatLinks.js
Appearance
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page. |
![]() | This user script seems to have a documentation page at User:Dudemanfellabra/AddCommonsCatLinks. |
/*
The following script places a button at the top of any list of sites on the National Register of Historic Places (NRHP).
When the button is clicked, the script looks in [[commons:Category:National Register of Historic Places with known IDs]]
to find any matches to the sites on the current list. If any are found, the user is prompted to add them or decline.
After all matches have been considered, the script edits the page to add in the commonscat links the user chose.
*/
// global vars
var thiswikitext=""
var CatTable=[];
var Rows=[];
var HTMLRows=[];
var currentRow=0
function FindCommonsCatButton() {
if (wgPageName.search("National_Register_of_Historic_Places_listings_in")==-1 && wgPageName!="User:Dudemanfellabra/Sandbox") {
return
}
if (location.href.indexOf('action')!=-1||location.href.indexOf('Talk:')!=-1) return
var button=document.createElement("input")
button.setAttribute("type", "button");
button.setAttribute("value", "Check for Commons categories");
button.setAttribute("id", "commonsbutton");
button.setAttribute("onclick", "CommonsClick()");
var content=document.getElementById('mw-content-text')
content.parentNode.insertBefore(button, content)
}
function CommonsClick() {
var button = document.getElementById('commonsbutton')
button.disabled = true
var ProgressDiv = document.createElement("div")
ProgressDiv.setAttribute("id", "ProgressDiv")
ProgressDiv.setAttribute("style", "width:500px; border:5px solid black; padding:5px; position:fixed; background:#ffffff; z-index:100")
ProgressDiv.style.left = "200px"
ProgressDiv.style.top = "150px"
commonsbutton.parentNode.insertBefore(ProgressDiv, commonsbutton)
ProgressDiv.innerHTML="Fetching wikitext... "
thiswikitext=getThisWikitext(wgPageName)
if (thiswikitext=="error"||thiswikitext=="") {
alert("Could not get wikitext! Script aborted!")
} else {
ProgressDiv.innerHTML+="Wikitext fetched!<br />Downloading Commons data."
GetFirst(ProgressDiv)
}
}
function getThisWikitext(title) {
try {
var output=JSON.parse(
$.ajax({
dataType: "json",
url: mw.util.wikiScript('api'),
data: {
format: 'json',
action: 'query',
prop: 'revisions',
rvprop: 'content',
titles: title,
indexpageids: true,
redirects: 'true'
},
async:false
})
.responseText
);
for (page in output.query.pages) {
wikitext = output.query.pages[page].revisions[0]['*'];
}
return wikitext
}
catch(err) {
return "error"
}
}
function GetFirst(ProgressDiv) {
$.ajax({
url: 'http://commons.wikimedia.org/w/api.php?action=query&list=categorymembers&format=json&cmtitle=Category%3ANational%20Register%20of%20Historic%20Places%20with%20known%20IDs&cmprop=title|sortkeyprefix&cmtype=subcat&cmlimit=max',
data: {
format: 'json'
},
dataType: 'jsonp',
success: function(jsonObject) { ProgressDiv.innerHTML+="."; GetMore(jsonObject,ProgressDiv)}
});
}
function GetMore(jsonObject,ProgressDiv) {
for (var c in jsonObject.query.categorymembers) {
var title=jsonObject.query.categorymembers[c].title.replace("Category:","")
var refnum=jsonObject.query.categorymembers[c].sortkeyprefix.trim()
CatTable[CatTable.length] = [title,refnum]
}
if (jsonObject["query-continue"]) {
$.ajax({
url: 'http://commons.wikimedia.org/w/api.php?action=query&list=categorymembers&format=json&cmtitle=Category%3ANational%20Register%20of%20Historic%20Places%20with%20known%20IDs&cmprop=title|sortkeyprefix&cmtype=subcat&cmcontinue='+jsonObject["query-continue"].categorymembers.cmcontinue+'&cmlimit=max',
data: {
format: 'json'
},
dataType: 'jsonp',
success: function(jsonObject) {ProgressDiv.innerHTML+="."; GetMore(jsonObject,ProgressDiv)}
});
} else {
ProgressDiv.innerHTML+=" Done!<br />Checking for matches... "
GotAll(ProgressDiv)
}
}
function GotAll(ProgressDiv) {
ProgressDiv.style.top = "5px"
var AllHTMLRows=document.getElementsByTagName("tr")
for (var i=0; i<AllHTMLRows.length; i++){
if (AllHTMLRows[i].className.indexOf("vcard")!=-1) HTMLRows.push(AllHTMLRows[i])
}
var index, RowLocations = [];
var str = "{{NRHP row"
var skip = str.length
var StartIndex = 0
while ((index = thiswikitext.indexOf(str, StartIndex)) > -1) {
var endtable = thiswikitext.indexOf("|}",StartIndex)
if (endtable<index&&endtable>-1) {
RowLocations.push(endtable)
StartIndex = endtable + 2
} else {
RowLocations.push(index);
StartIndex = index + skip;
}
}
RowLocations.push(thiswikitext.indexOf("|}",StartIndex)) // last row ends at end of last table
for (var i=0; i<RowLocations.length-1; i++) {
var temp=thiswikitext.substr(RowLocations[i],RowLocations[i+1]-RowLocations[i])
if (temp.indexOf("{{NRHP row")>-1) Rows.push(temp)
}
currentRow=0
CheckRow(currentRow)
}
function CheckRow(i) {
if (i==Rows.length) {
editPageWithCommonsCat({
title: wgPageName,
text: thiswikitext,
summary: 'Semi-automated addition of commonscat links using [[User:Dudemanfellabra/Sandbox.js|script]].'
});
return;
}
HTMLRows[i].scrollIntoView() // highlight current row
window.scrollBy(0,-100)
var Matches=[]
var refnum=Rows[i].match(/\|[ ]*?refnum[ ]*?=.*?[\n|\|]/g)[0]
refnum=refnum.replace(/\|[ ]*?refnum[ ]*?=/g,"").replace(/[\n|\|]/g,"").replace(/[^0-9,]/g,"").split(",")
var name=Rows[i].match(/\|[ ]*?name[ ]*?=.*?[\n|\|]/g)[0]
name=name.replace(/\|[ ]*?name[ ]*?=/g,"").replace(/[\n|\|]/g,"").trim()
var commonscat=Rows[i].match(/\|[ ]*?commonscat[ ]*?=.*?[\n|\|]/g)
if (commonscat!=null) {
commonscat=commonscat[0].replace(/\|[ ]*?commonscat[ ]*?=/g,"").replace(/[\n|\|]/g,"").trim()
if (commonscat!="") {
// check to see if image is present and allow user to choose one
currentRow++
CheckRow(currentRow) // skip if already has user-specified commonscat and image
return
}
}
for (var j=0; j<refnum.length; j++) {
for (var k=0; k<CatTable.length; k++) {
if (refnum[j]==CatTable[k][1]) Matches[Matches.length]=CatTable[k]
}
}
if (Matches.length!=0) {
ChooseCat(Matches,refnum,name)
} else {
currentRow++
CheckRow(currentRow)
}
}
function ChooseCat(Matches,refnum,name) {
var fieldset = document.createElement("fieldset");
fieldset.setAttribute("style","margin:0px")
var legend = document.createElement("legend");
legend.innerHTML=name+" (#"+refnum+") matches the following categories:"
fieldset.appendChild(legend);
fieldset.innerHTML+="Select one to add:<br />"
for (var j=0; j<Matches.length; j++) {
var cat = document.createElement("input")
cat.setAttribute("type","radio")
cat.setAttribute("name","catselect")
cat.setAttribute("id","cat"+j)
if (j==0) cat.setAttribute("checked","checked")
fieldset.appendChild(cat);
var catlabel = document.createElement("label")
catlabel.setAttribute("for","cat"+j)
catlabel.innerHTML=Matches[j][1]+" – <a href='http://commons.wikimedia.org/wiki/Category:"+Matches[j][0]+"' target=;_blank'>"+Matches[j][0]+"</a>"
fieldset.appendChild(catlabel);
fieldset.innerHTML+="<br />"
}
var skip = document.createElement("input")
skip.setAttribute("type","radio")
skip.setAttribute("name","catselect")
skip.setAttribute("id","skip")
fieldset.appendChild(skip);
var skiplabel = document.createElement("label")
skiplabel.setAttribute("for","skip")
skiplabel.innerHTML="Do not add any category"
fieldset.appendChild(skiplabel);
fieldset.innerHTML+="<br />"
var selectbutton=document.createElement("input")
selectbutton.setAttribute("type", "button")
selectbutton.setAttribute("value", "Select")
selectbutton.setAttribute("style","margin-top:7px")
selectbutton.setAttribute("onclick", "CatChosen()");
fieldset.appendChild(selectbutton)
var overlay = document.createElement("tr")
var td=document.createElement("td")
td.setAttribute("colspan",HTMLRows[currentRow].getElementsByTagName("td").length+1)
overlay.appendChild(td)
td.appendChild(fieldset)
overlay.setAttribute("style", "outline:2px solid red; border-top:0px; background:#ffffff")
overlay.setAttribute("id","overlay")
HTMLRows[currentRow].setAttribute("style","border-bottom:0px;")
HTMLRows[currentRow].parentNode.insertBefore(overlay, HTMLRows[currentRow].nextSibling)
}
function CatChosen() {
var overlay=document.getElementById("overlay")
var options=overlay.getElementsByTagName("input")
var titles=overlay.getElementsByTagName("label")
for (var i=0; i<options.length-1; i++) {
if (options[i].checked) {
var link=titles[i].getElementsByTagName("a")
if (link.length==0) continue // if chose not to add cat
var catname=link[0].innerHTML
var tempRow = Rows[currentRow]
tempRow = tempRow.substr(0,tempRow.length-4)+"\n|commonscat="+catname+"\n}}\n"
thiswikitext=thiswikitext.replace(Rows[currentRow],tempRow)
}
}
overlay.parentNode.removeChild(overlay)
currentRow++
CheckRow(currentRow)
}
function editPageWithCommonsCat(info,ProgressDiv) {
var ProgressDiv=document.getElementById("ProgressDiv")
ProgressDiv.innerHTML+="Done!<br />Editing page... "
$.ajax({
url: mw.util.wikiScript( 'api' ),
type: 'POST',
dataType: 'json',
async: false,
data: {
format: 'json',
action: 'edit',
title: info.title,
text: info.text,
summary: info.summary,
token: mw.user.tokens.get( 'editToken' )
}
})
.done (function( data ) {
if (data && data.edit && data.edit.result && data.edit.result == 'Success') {
ProgressDiv.innerHTML+="Done! Refresh the page to see the result!"
} else {
ProgressDiv.innerHTML += " The edit query returned an error."
}
})
.fail (function() {
alert('Ajax failure.');
});
}
addOnloadHook(FindCommonsCatButton);