User:Krinkle/Scripts/iterate-sitematrix.js

From Meta, a Wikimedia project coordination wiki

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/**
 * Iterate over all Wikimedia Foundation wikis using the SiteMatrix API.
 *
 * See also:
 * - <https://meta.wikimedia.org/wiki/User:Krinkle/Tools/Global_SUL>
 *
 * @revision 2012-01-29 <https://meta.wikimedia.org/wiki/User:Krinkle/Scripts/iterate-sitematrix.js>
 * @example
 * <code>
 * var it = new mw.siteMatrix.Iterator({
 *     centralApiPath: mw.util.wikiScript('api'),
 *     // iterator {Iterator}
 *     // wikiObj {Object}: contains 'url', 'dbname' and maybe 'private'
 *     // iterationNr {Number}: starting at 0
 *     // listLength {Number}: length of list iteration array
 *     onIteration: function (iterator, wikiObj, iterationNr, listLength) {
 *         iterator.next();
 *     },
 *     onComplete: function (iterator, wikiObj, listLength) {
 *     }
 * });
 * it.start();
 * </code>
 *
 * @param options {Object}
 * - centralApiPath string: Path to api of a wiki that has the SiteMatrix installed
 * - onIteration function: callback for action on each wiki
 */
if (mw.siteMatrix === undefined) {
	mw.siteMatrix = {};
}
mw.siteMatrix.Iterator = function Iterate(options) {
	var methods, i, current, list, instance = this;
	if (!options.centralApiPath || !options.onIteration) {
		throw new Error('Invalid arguments');
	}
	if (!(this instanceof mw.siteMatrix.Iterator)) {
		throw new TypeError('Illegal function call');
	}
	instance.start = function start() {
		if (i !== undefined) {
			throw new Error('Cannot start twice');
		}
		$.getJSON(options.centralApiPath + '?format=json&action=sitematrix&callback=?', function (data) {
			i = 0;
			list = [];
			if (!data || !data.sitematrix) {
				return;
			}
			$.each(data.sitematrix, function (key, value) {
				var group, wi, wo;
				if (key === 'count') return;
				group = key === 'specials' ? value : value.site;
				if ($.isArray(group) && group.length) {
					for (wi = 0; wi < group.length; wi += 1) {
						 // Only public wikis
						if (group[wi].private === undefined && group[wi].closed === undefined && group[wi].fishbowl === undefined) {
							list.push(group[wi]);
						}
					}
				}
			});
			instance.next();
		});
	};
	instance.next = function next() {
		if (i < list.length) {
			current = list[i];
			options.onIteration(instance, current, i, list.length);
			i += 1;
		} else {
			options.onComplete(instance, current, list.length);
		}
	};
	return instance;
};