User:RP88/gallery.js

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search
Note: After saving, you have to bypass your browser's cache to see the changes. Internet Explorer: press Ctrl-F5, Mozilla: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Opera/Konqueror: press F5, Safari: hold down Shift + Alt while clicking Reload, Chrome: hold down Shift while clicking Reload.
//tool that creates a gallery of the current search results and saves 
function httpGet(theUrl) {
    var xmlHttp = null;
 
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", theUrl, false);
    xmlHttp.send(null);
    return xmlHttp.responseText;
}

function getedittoken() {
    var jsonStr = httpGet("/w/api.php?action=query&prop=info&intoken=edit&titles=Main%20Page&format=json");
	var json = JSON.parse(jsonStr);
	var items = json["query"]["pages"];
	for (var key in items) {
		return items[key]['edittoken'];
	}
}

function saveGallery(gallery, query) {
    var editToken = getedittoken();
    $.ajax({
        url: mw.util.wikiScript( 'api' ),
        data: {
            format: 'json',
            action: "edit",
            title: galleryPage,
            summary: "query: '" + query + "'",
            text: gallery,
            token: editToken
        },
        dataType: 'json',
        type: 'POST',
        success: function( data ) {
            if ( data && data.edit && data.edit.result == 'Success' ) {
                alert(galleryPage + " updated!");
            } else if ( data && data.error ) {
                alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info );
            } else {
                alert( 'Error: Unknown result from API.' );
            }
        },
        error: function( xhr ) {
            alert( 'Error: Request failed.' );
        }
    });
}

// main method
if (typeof galleryPage === 'undefined') {
	alert("Variable 'galleryPage' must be defined before executing this script!");
	exit();
}

//var element = document.getElementById("powerSearchText");
var element = document.getElementById("searchText");
if (element===null) {
	alert("Please first perform a search and then use this feature!");
	exit();
}
var query = element.getAttribute("value");

var offset = 0;
var maxLoops = 50;
var res = "<gallery>\n";
var fileCnt = 0;
for (var i=0;i<maxLoops;i++) {
	var jsonStr = httpGet("/w/api.php?format=json&srlimit=max&list=search&srlimit=max&action=query&continue=&srnamespace=6&srsearch=" + query + "&sroffset=" + offset);

	var json = JSON.parse(jsonStr);
	var items = json["query"]["search"];

	for (var key in items) {
		res += items[key]["title"] + "\n";
		fileCnt++;
	}
	if (typeof json["continue"] != 'undefined') {
		offset = json["continue"]["sroffset"];
    } else {
      	break;
    }
}
res += "</gallery>";
if (confirm("Updating '" + galleryPage + "' with a gallery containing " + fileCnt + " files?")) {
	saveGallery(res, query);
}