Usuario:Chieftain Alex/Wiki javascripts

De Guild Wars 2 Wiki
Ir a la navegaciónIr a la búsqueda
<div id="apidata"> (nothing is loading until you paste a script from below into your javascript scratchpad)</div>
(nothing is loading until you paste a script from below into your javascript scratchpad)

Category pages[editar]

/* GW2W API query tool for all pages in a category */
console.log('User pressed run. Starting queries for Special:Category');
var category_page = 'Category:' + 'Bestiary screenshots';

// Wrapper function to return the results once complete
function apiWrapper (config, callbackfunction) {
    // Fetch all the pages
    function apiQuery (config, token) {
        var url = config.baseurl;
        if (token) {
            url += '&' + config.continue + '=' + token;
        }
        $.getJSON(url).done(function(data){
            // Add results to stack
            config.tempresultsarray.push(data['query'][config.output]);

            // Get further results if available
            if (data['continue']) {
                apiQuery(config, data['continue'][config.continue]);
            } else {
                // Flatten data from nested arrays to one array of result objects
                config.resultsarray = $.map(config.tempresultsarray, function(v) {
                    return v;
                });
                console.log('Query complete.');

                // Call the next function
                callbackfunction(config);
            }
        });
    }
    apiQuery(config);
}

// Function to convert an object variable into a table
function makeTableHTML (config) {
    var data = config.resultsarray;

    // Generate table html
    var result = '<table class="wikitable"><tbody>';
    if (data.length > 0) {
        var columns = Object.keys(data[0]);
        result += '<tr>' + $.map(columns, function(c) { return '<th>' + c + '</th>'; }).join('') + '</tr>';
        result += $.map(data, function(v) {
            return '<tr>' + $.map(columns, function(c) {
                return '<td>' + v[c] + '</td>';
            }).join('') + '</tr>';
        }).join('\n');
    }
    result += '</tbody></table>';
    $('#mw-content-text').html(result);
}

// Make request
apiWrapper({
  baseurl: 'https://wiki-es.guildwars2.com/api.php?format=json&action=query&list=categorymembers&cmlimit=500&cmtitle=' + category_page,
  output: 'categorymembers',
  continue: 'cmcontinue',
  tempresultsarray: [],
  resultsarray: []
}, makeTableHTML);

Interwiki for custom list[editar]

/* GW2W API query tool for language links. */
// Function to convert an object variable into a table
function makeTableHTML(data) {
    var result = '<table class="table mech1" style="margin-bottom:0px;"><tr><th>ES page (this wiki)</th><th>DE page</th><th>EN page</th><th>FR page</th></tr>';
    $.each(data, function(index, val) {
        if (typeof val['langlinks'] !== 'undefined'){
            // Add english page title
            result += '<tr>' + '<td>'+val['title']+'</td>';

            // Placeholder with all interwiki language keys
            var resultobj = { de: '', en: '', fr: '' };

            // Go through each interwiki on the page and add them into the object
            $.map(val['langlinks'], function(v){
                resultobj[v['lang']] = v['*'];
            });

            // Add to the results
            result += $.map(resultobj, function(v){
                return '<td>' + v + '</td>';
            }).join('\n');
            result += '</tr>';
        } else {
            result += '<tr>' + '<td>'+val['title']+'</td><td>...</td><td>...</td><td>...</td></tr>';
        }
    });
    result += '</table>';
    return result;
}

// Fetch all the possible itemsIDs
(function fetchAPIData() {

var ids = [
"Receta: Antorcha matadragones carmesí",
"Receta: Apaleador perlado de expedicionario",
"Receta: Zapatos del enviado refinados"
];

        console.log('Number of pages: ' + ids.length);

        // Query API until all the page ids have been requested
        var promises = [], baseurl = 'https://wiki-es.guildwars2.com/api.php?action=query&format=json&prop=langlinks&lllimit=500&titles=';
        var lines = [[]], maxlength = 1000, j = 0, running_count = 0, running_total = 0;
        for (var i=0; i<ids.length; i++) {
            if ((running_total + ids[i].length) >= maxlength || running_count > 50) {
                j += 1;
                lines.push([]);
                running_count = 0;
                running_total = 0;
            }
            running_count += 1;
            running_total += 1 + ids[i].length;
            lines[j].push(ids[i]);
        }
        for (var k=0; k<lines.length; k++) {
            var promise = $.getJSON(baseurl + lines[k].join('|') );
            promises.push(promise);
        }

        // Wait until all the GET requests have finished
        $.when.apply($,promises).done(function() {
            var newarguments = {};
            if ( promises.length > 1 ) { newarguments = arguments; } else { newarguments[0] = arguments; }

            console.log(newarguments);
            var alldata = [];
            $.each(newarguments, function(i,v){
              $.each(v[0]['query']['pages'], function(ii,vv){
                alldata.push(vv);
              });
            });

            // Write to document
            $('#apidata').html(makeTableHTML(alldata));
        });

})();

Template parameter check[editar]

/* GW2W API query tool for Template parameters */
function apiQuery () {
    mw.loader.using('mediawiki.api.parse', function () {
        var template = 'Enseña receta';
        var category = 'Hojas de receta';
        var parameters = '1';
        var firstquery = '{{User:Chieftain Alex/Templates/Parameter check|mode=1|template='+template+( category != '' ? ('|category=' + category) : '' )+'}}';

        var api = new mw.Api();
        api.parse(firstquery).done(function (resulttext) {

            // Find the output token
            var pattern = /\<div class\="apiresults"\>(\d+)\<\/div\>/;
            var m = resulttext.match(pattern);
            console.log('regexp', m);

            // Check something matched
            if (!m) {
                console.log('No regular expression matched, quitting.')
                return;
            }

            // Convert match from text into a number.
            var n = Number(m[1]);
            if (n == 0) {
                console.log('Zero results found, quitting.');
            } else {
                console.log(n, ' results found, querying...');

                // Repeat query n/500 times until done
                var promises = [];
                for (var i=0; i<n; i+=500) {
                    var furtherquery = '{{User:Chieftain Alex/Templates/Parameter check|mode=2|template='+template+( category != '' ? ('|category=' + category) : '' )+'|parameters='+parameters+'|offset='+i+'}}';
                    promises.push(api.parse(furtherquery));
                }

                // Wait until all the GET requests have finished
                $.when.apply($,promises).done(function() {
                    // Concatenate the api results
                    var table = $.map(arguments, function(v) { return v; }).join('\n');

                    // Write to document
                    $('#apidata').html(table);

                    // Replace first column PAGENAME with FULLPAGENAME (i.e. add namespace)
                    $.map($('#apidata td:first-child a') ,function(v,i){ $(v).text( v.title ); });

                    // Now copy the output to excel, then remove duplicates including table headings.
                    console.log('Batch query complete.');
                });
            }
        });
    });
}
apiQuery();

WhatLinksHere with misc inputs[editar]

/* GW2W API query tool for SMW results for miscellaneous page inputs */
function apiQuery () {
    mw.loader.using('mediawiki.api.parse', function () {
        var pages = ["Asta de báculo verde"];

        var api = new mw.Api();

        // Break the list of pages down into a url almost 2000 characters long.
        var lines = [[]], maxlength = 1800, j = 0, running_count = 0, running_total = 0;
        for (var i=0; i<pages.length; i++) {
            if ((running_total + pages[i].length) >= maxlength || running_count > 100) {
                j += 1;
                lines.push([]);
                running_count = 0;
                running_total = 0;
            }
            running_count += 1;
            running_total += 3 + pages[i].length;
            lines[j].push(pages[i]);
        }
        // Submit each request, result is returned as a table.
        var promises = [];
        for (var k=0; k<lines.length; k++) {
            var current_pages = lines[k].join('\n');
            var parsetext = '{{Usuario:Chieftain Alex/Templates/WhatLinksHere query|1='+current_pages+'}}';
            promises.push(api.parse(parsetext));
        }

        // Wait until all the GET requests have finished
        $.when.apply($,promises).done(function() {
            // Concatenate the api results
            var table = $.map(arguments, function(v) { return v; }).join('\n');

            // Write to document
            $('#apidata').html(table);

            // Now copy the output to excel, then remove duplicates including table headings.
            console.log('Batch query complete.');
        });
    });
}
apiQuery();