User:Void/createWikiNotify.js

// // TODO: more translations

var cwn = { ca: { submit: 'Enviar', c_domain: 'Marca aquesta wiki com que necessita un domini personalitzat', i: { required: 'Si us plau, ompli tots els camps obligatoris.', user: 'El sol·licitant no sembla existir.', dbexists: 'La wiki sol·licitada ja existeix.', unknown: 'Hi ha un problema amb la seva entrada o amb createWikiNotify.js', self: 'Wiki requester matches current user, skipping notification', dbname: 'The requested dbname contains invalid characters\nPlease be aware that only alphanumeric characters can be present in a dbname' },		summary: 'Wiki creada' },	de: { submit: 'Absenden', c_domain: 'Mark this wiki as needing a custom domain', i: { required: 'Please fill in all the required fields.', user: 'Der anfrager ist nicht erstellt auf dieser Wiki-Farm.', dbexists: 'Eine Wiki mit dem Database-namen besteht schon.', unknown: 'There is a problem with your input or with createWikiNotify.js', self: 'Wiki requester matches current user, skipping notification', dbname: 'The requested dbname contains invalid characters\nPlease be aware that only alphanumeric characters can be present in a dbname' },		summary: 'Wiki created' },	en: { submit: 'Submit', c_domain: 'Mark this wiki as needing a custom domain', i: { required: 'Please fill in all the required fields.', user: 'The requester does not appear to exist.', dbexists: 'The requested wiki already exists.', unknown: 'There is a problem with your input or with createWikiNotify.js', self: 'Wiki requester matches current user, skipping notification', dbname: 'The requested dbname contains invalid characters\nPlease be aware that only alphanumeric characters can be present in a dbname' },		summary: 'Wiki created (using CWNotify)' },	es: { submit: 'Enviar', c_domain: 'Marcar esta wiki como que necesita un dominio personalizado', i: { required: 'Por favor, rellene todos los campos obligatorios.', user: 'El solicitante no parece existir.', dbexists: 'La wiki solicitada ya existe.', unknown: 'Hay un problema con su entrada o con createWikiNotify.js', self: 'Wiki requester matches current user, skipping notification', dbname: 'The requested dbname contains invalid characters\nPlease be aware that only alphanumeric characters can be present in a dbname' },		summary: 'Wiki creada (usando CWNotify)' },	fr: { submit: 'Soumettre', c_domain: 'Marquer ce wiki nécessitant un domaine personnalisé', i: { required: 'Merci de remplir tout les champs requis.', user: 'Le demandeur n existe pas.', dbexists: 'Ce wiki existe déjà.', unknown: 'Il y a une problème avec votre entrée ou avec createWikiNotify.js', self: 'Wiki requester matches current user, skipping notification', dbname: 'The requested dbname contains invalid characters\nPlease be aware that only alphanumeric characters can be present in a dbname' },		summary: 'Wiki created' },	nl: { submit: 'Opslaan', c_domain: 'Mark this wiki as needing a custom domain', i: { required: 'Vul alle verplichte velden in.', user: 'De aanvrager lijkt niet te bestaan.', dbexists: 'Deze wiki bestaat al.', unknown: 'Er is een probleem met het formulier of createWikiNotify.js', self: 'Wiki requester matches current user, skipping notification', dbname: 'The requested dbname contains invalid characters\nPlease be aware that only alphanumeric characters can be present in a dbname' },		summary: 'Wiki aangemaakt' },	pt: { submit: 'Enviar', c_domain: 'Marca esta wiki como você precisa de um domínio personalizado', i: { required: 'Por favor, preencha todos os campos obrigatórios.', user: 'O requerente não parece existir.', dbexists: 'O wiki solicitada já existe.', unknown: 'Há um problema com a sua entrada ou createWikiNotify.js', self: 'Wiki requester matches current user, skipping notification', dbname: 'The requested dbname contains invalid characters\nPlease be aware that only alphanumeric characters can be present in a dbname' },		summary: 'Wiki criada' },	tl: { submit: 'Isumite', c_domain: 'Markahan ang wiking ito bilang nangangailangan ng isang pasadyang dominyo', i: { required: 'Pakipunan ang lahat ng mga kinakailangang patlang.', user: 'Nagmumukhang hindi umiiral ang tagapaghiling.', dbexists: 'Umiiral na ang hinihiling na wiki.', unknown: 'May problema sa iyong input o sa createWikiNotify.js', self: 'Tumutugma ang tagapaghiling ng wiki sa kasalukuyang tagagamit, nilalagpasan ang abiso', dbname: 'The requested dbname contains invalid characters\nPlease be aware that only alphanumeric characters can be present in a dbname' },		summary: 'Ginawa ang wiki (gamit ang CWNotify)' }, };

function getTrans(lang) { if(cwn[lang]) return cwn[lang]; else return cwn.en; }

/*if( /Special:RequestWikiQueue/.test(mw.config.get('wgPageName')) && $('form[action="/wiki/' + mw.config.get('wgPageName') + '"]').children.children.children.children.children[13].textContent !== "" ) { $('a[title="Special:CreateWiki"]')[0].href += '&cwCustom=1'; // Hack in a way to tell wiki requests with a custom domain apart from those that don't }*/

if( mw.config.get('wgPageName') === 'Special:CreateWiki' && $("#mw-input-cwRequester")[0].childNodes[0].value !== mw.config.get('wgUserName') ) { var userLang = mw.user.options.get('language'); var messages = getTrans(userLang); mw.loader.using( ['oojs-ui', 'mediawiki.util'] ).done( function {		var submit = new OO.ui.ButtonWidget({ label: messages.submit, id: 'c-submit-button' });		var customCBox = new OO.ui.CheckboxInputWidget({ selected: window.location.toString.includes('cwCustom=1') ? true : false, id: 'c-custom-cbox' });		var fieldset = new OO.ui.FieldsetLayout( { } );		fieldset.addItems( [ new OO.ui.FieldLayout( customCBox, {label: messages.c_domain, align: 'inline'} ) ] );		$('div.mw-htmlform-submit-buttons').replaceWith(submit.$element.css('margin-top', '1em'));		$('#mw-input-cwDBname').after(fieldset.$element.css('margin-top', '1em'));		$('#c-submit-button').click(function{ // Validate input $('#c-submit-button').css("display", "none"); // Prevent double submissions (hopefully) var dbname = $("#mw-input-cwDBname")[0].childNodes[0].value; var requester = $("#mw-input-cwRequester")[0].childNodes[0].value; var reason = $("#mw-input-wpreason")[0].childNodes[0].value; if( dbname.trim.length === 0 || requester.trim.length === 0 || reason.trim.length === 0 ) invalidInput('required'); else if ( /[^A-Za-z0-9]/.test(dbname.trim) ) invalidInput('dbname'); else { if( /[A-Z]/.test(dbname) ) $("#mw-input-cwDBname")[0].childNodes[0].value = dbname.toLowerCase; validateUser(requester); }		});	} ); }

function validateUser(user) { $.getJSON(		mw.util.wikiScript('api'),		{			format: 'json',			action: 'query',			list: 'users',			ususers: user,			usprop: ''		}	).success(function (data){		if( mw.config.get('wgUserName') === user ) {			invalidInput('self');			$('form')[0].submit;		}		else if(typeof data.query.users[0].missing === 'undefined')			validateDB;		else			invalidInput('user');	}); }

function validateDB { var dbname = $("#mw-input-cwDBname")[0].childNodes[0].value; $.getJSON(		mw.util.wikiScript('api'),		{			format: 'json',			action: 'wikidiscover'		}	).success( function(data) {		var wikis = data.wikidiscover;		for(var i = 0; i < wikis.length; i++) {			if(wikis[i].dbname == dbname)				return invalidInput('dbexists'); // Exists		}		validInput; // Does not exist	} ); }

function invalidInput(type) { var reason; if(messages.i[type]) reason = messages.i[type]; else reason = messages.i.unknown; alert(reason); $('#c-submit-button').css("display", "block"); }

function validInput { var dbname = $("#mw-input-cwDBname")[0].childNodes[0].value; var lang = $("#mw-input-cwLanguage")[0].childNodes[0].value; var requester = $("#mw-input-cwRequester")[0].childNodes[0].value; var custom = $('#c-custom-cbox')[0].childNodes[0].checked; var suffix = lang; if( suffix === 'en' ) suffix = ''; else suffix = '/' + suffix; var template = 'Template:Wiki created' + (custom ? '(CD)' : '') + suffix; dbname = dbname.slice(0, dbname.lastIndexOf('wiki')); // Check if the template exists and edit based off response $.getJSON(		mw.util.wikiScript('api'),		{			format: 'json',			action: 'query',			titles: template,			prop: 'revisions',			rvlimit: 1,			rvprop: '' // Don't need anything to see if it's there		}	).success(function(data){edit(data, template, requester, dbname, lang);}); }

function edit (resp, template, requester, dbname, lang) { if( resp.query.pages[-1] ) template = template.slice(0, template.indexOf('/')).slice(template.indexOf(':') + 1); // No translated version, default to en	else template = template.slice(template.indexOf(':') + 1); // Remove template prefix

$.getJSON(		mw.util.wikiScript('api'),		{			format: 'json',			action: 'query',			titles: 'User talk:' + requester,			prop: 'revisions',			rvlimit: 1,			rvprop: 'content'		}	).success(function(resp) {		if( resp.query.pages[-1] ) {			// Didn't find, create page			$.ajax( { url: mw.util.wikiScript('api'), type: 'POST', dataType: 'json', data: { format: 'json', action: 'edit', token: mw.user.tokens.get('csrfToken'), title: 'User talk:' + requester, text: 'https://' + dbname + '.miraheze.org', summary: getTrans(lang).summary, createonly: 1 // Force only create page }			} ).success(function{$('form[action="/wiki/Special:CreateWiki"]')[0].submit});		}		else {			// Found, preserve existing content			var wtext = JSON.stringify(resp);			wtext = wtext.slice(wtext.indexOf('"*":"') + 5, wtext.indexOf('"}]}'));			wtext = wtext.replace(/\\n/g, '\n'); // JSON.stringify escapes the string			wtext = wtext.replace(/\\"/g, '"');			wtext += '\n\nhttps://' + dbname + '.miraheze.org',			$.ajax( { url: mw.util.wikiScript('api'), type: 'POST', dataType: 'json', data: { format: 'json', action: 'edit', token: mw.user.tokens.get('csrfToken'), title: 'User talk:' + requester, text: wtext, summary: getTrans(lang).summary, }			} ).success(function{$('form[action="/wiki/Special:CreateWiki"]')[0].submit});		}	} ); } //