Jump to content

User:Opencooper/domainRedirect.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Opencooper (talk | contribs) at 10:43, 2 May 2019 (tweak). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
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.
/* Determine whether or not the current article has a redirect from its URL pointing to it */

function setup() {
    // If we're not reading an article, do nothing
    if (!(mw.config.get("wgAction") === "view"
          && mw.config.get("wgIsArticle")
          && !location.search.split('oldid=')[1]
          && mw.config.get("wgPageName") !== "Main_Page")) {
        return;
    }
    
    getWikidata();
}

// First try to get the official site off Wikidata
function getWikidata() {
    var wikidataId = mw.config.get( 'wgWikibaseItemId' );
    if (wikidataId === null) {
        getInfobox();
        return;
    }

    // API docs: https://www.wikidata.org/w/api.php?action=help&modules=wbgetclaims
    var url;
    $.ajax({
        url: "https://www.wikidata.org/w/api.php",
        data: {
            action: "wbgetclaims",
            entity: wikidataId,
            property: "P856",
            languages: "en",
            format: "json",
            origin: "*"
        },
        success: function(response) {
            if (typeof response.claims.P856 != "undefined") {
                wikidataUrl = response.claims.P856[0].mainsnak.datavalue.value;
                retrievalMethod = "wikidata";
                getRedirects(wikidataUrl);
            } else {
                // console.log("domainRedirect.js: Wikidata failed");
                getInfobox();
            }
        }
    });
}

// Then try getting a website in the infobox
function getInfobox() {
    var infoboxUrl;

    // Get {{Url|}}
    infoboxUrl = $(".infobox .url a").last().attr("href");    
    if (infoboxUrl) {
        retrievalMethod = "{{Url}}";
        getRedirects(infoboxUrl);
        return;
    } else {
    	// console.log("domainRedirect.js: Infobox {{Url}} failed");
    }

    // Get |website= 
    $(".infobox tr").each(function() {
        if ($(this).children("th").text() == "Website") {
            infoboxUrl = $(this).children("td").children("a").attr("href");
            return false;
        }
    });
    
    if (infoboxUrl) {
        retrievalMethod = "website=";
        getRedirects(infoboxUrl);
    } else {
        // console.log("domainRedirect.js: Infobox website= failed");
        getExternals();
    }
}

// Finally, try to get it from the external links
function getExternals() {
    // First try getting {{official website}}
    var officialUrl = $(".official-website a").first().attr("href");
    if (officialUrl) {
    	retrievalMethod = "{{official site}}";
        getRedirects(officialUrl);
        return;
    } else {
        // console.log("domainRedirect.js: No official site");
    }
    
    // Then try the external links section and the first link that says official
    var externalUrl = $("h2").has("#External_links").nextUntil("h2").find("li a.external").first();
    if (externalUrl && /Official/i.test(externalUrl.text())) {
    	var externalHref = externalUrl.attr("href");
    	retrievalMethod = "§External_links";
        getRedirects(externalHref);
    } else {
        // console.log("domainRedirect.js: No external links list found");
        console.info("domainRedirect.js: No candidates found");
    }
}

function getRedirects(candidateUrl) {
    // API docs: https://www.mediawiki.org/wiki/API:Redirects
    $.ajax({
        url: "https://en.wikipedia.org/w/api.php",
        data: {
            action: "query",
            prop: "redirects",
            format: "json",
            titles: mw.config.get("wgPageName"),
            rdprop: "title",
            rdshow: "!fragment",
            rdlimit: "max"
        },
        success: function(response) {
            var pageId = mw.config.get("wgArticleId");
            var redirectObject = response.query.pages[pageId];
            if (typeof redirectObject.redirects != "undefined") {
                redirects = redirectObject.redirects;
                checkRedirectExistence(redirects, candidateUrl);
            } else {
                // console.log("domainRedirect.js: No inbound redirects");
                displayCandidate(candidateUrl);
            }
        }
    });
}

function checkRedirectExistence(redirects, candidateUrl) {
    for (var r of redirects) {
        var title = r.title;
        if (!/\./.test(title)) {
            continue;
        }

        // console.log("domainRedirect.js: Looking for " + title + " in " + candidateUrl);

        // We search for the title inside the URL, but we could always use the hostname
        var titleEscaped = mw.RegExp.escape(title);
        var re = new RegExp(titleEscaped, "i");

        if (re.test(candidateUrl)) {
            console.info("domainRedirect.js: Domain redirect already present: " + title);
            return;
        }
    }
    
    displayCandidate(candidateUrl);
}

function displayCandidate(candidateUrl) {
    var pageTitle = mw.config.get("wgPageName").replace(/_/g, " ");
    var parser = new URL(candidateUrl);
    var candidateDomain = parser.hostname;
    candidateDomain = candidateDomain.replace(/^w+\d*\./, ""); // get rid of www


    var createUrl = "https://en.wikipedia.org/w/index.php?title=" + candidateDomain + "&action=edit";
    var preload = "&preload=User:Opencooper/domainRedirectPreloads.js&preloadparams[]=" + pageTitle
                  +"&summary=Create%20redirect%20%28using%20%5B%5BUser%3AOpencooper%2FdomainRedirect.js%7CdomainRedirect.js%5D%5D%29";
    var createLink = "<a href='" + createUrl + preload + "' title='via "
                     + retrievalMethod + ": " + candidateUrl + "'>"
                     + candidateDomain + "</a>";
    $("#contentSub").append("<span class='mw-redirectedfrom' id='domainRedirect'>"
                            + "&nbsp;&nbsp;(Possible domain redirect: "
                            + createLink + ")</span>");
}

var retrievalMethod;
$(setup);