Jump to content

User:Dudemanfellabra/AddCommonsCatLinks.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Dudemanfellabra (talk | contribs) at 20:52, 18 April 2014 (code to find commonscat matches). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)
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.
/*
   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);