मीडियाविकि:Gadget-afchelper.js/core.js

विकिपिडिया, एक स्वतन्त्र विश्वकोशबाट
सूचना: सम्पादनहरू प्रकाशित गरेपछि, परिवर्तनहरू हेर्नको लागि तपाईंले आफ्नो ब्राउजरको क्यासलाई बाइपास गर्नुपर्छ। गुगल क्रोम, फायरफक्स, माइक्रोसफ्ट एजसफारी: Shift कुञ्जी थिचिराखेर रिलोड उपकरणपट्टी बटनमा थिच्नुहोस्।
/* Uploaded from https://github.com/WPAFC/afch, commit: a5cf7509fb65f7b6478ddaf51dff332ce1b2bc3a (beta) */
//<nowiki>
// Script should be located at [[MediaWiki:Gadget-afchelper-beta.js/core.js]]

function jqEsc(expression) {
	return expression.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~ ]/g, ''); 
}

importScript('User:Timotheus Canens/displaymessage.js');
var afchelper_baseurl = mw.config.get('wgServer') + '/w/index.php?action=raw&ctype=text/javascript&title=MediaWiki:Gadget-afchelper-beta.js';

var afcHelper_advert = ' ([[वि:लेसृ|लेसृसा]])';
var pagetext = '';
var usertalkpage = '';

// CSS stylesheet
mw.loader.load(mw.config.get('wgServer') + '/w/index.php?action=raw&ctype=text/css&title=MediaWiki:Gadget-afchelper-beta.css', 'text/css');

if (mw.config.get('wgPageName').indexOf('विकिपिडिया:लेख_सृजना/अनुप्रेषणहरू') !== -1) {
	mw.loader.load(afchelper_baseurl + '/redirects.js');
} else if (mw.config.get('wgPageName').indexOf('विकिपिडिया:फाइल_अपलोड') !== -1) {
	mw.loader.load(afchelper_baseurl + '/ffu.js');		
} else if ((mw.config.get('wgPageName').indexOf('विकिपिडिया:लेख_सृजना/') !== -1)
			|| (mw.config.get('wgPageName').indexOf('विकिपिडिया:लेख_सृजना/') !== -1)
			|| (mw.config.get('wgPageName').indexOf('User:') !== -1)
			|| (mw.config.get('wgPageName').indexOf('Draft:') !== -1)
			){
	mw.loader.load(afchelper_baseurl + '/submissions.js');				
}

// This enables the beta notice for all uses except the official gadget
if (afchelper_baseurl.indexOf('MediaWiki:'+'Gadget-afchelper.js' /* hack to stop upload scripts from find+replacing this */) == -1)
	var BETA = true;
else
	var BETA = false;

if (BETA) {
	// Manually load mw.api() and chosen only if we're not using the gadget...with the gadget, they are already dependencies
	mw.loader.load('mediawiki.api');
	mw.loader.load('jquery.chosen');
	// Set the summary to denote that we're using a "beta" version of the script
	var afcHelper_advert = ' ([[वि:लेसृ|लेसृसा]] बेटा)';
}

function afcHelper_generateSelect(title, options, onchange) {
	var text = '<select name="' + title + '" id="' + title + '" ';
	if (onchange !== null) text += 'onchange = "' + onchange + '" ';
	text += '>';
	for (var i = 0; i < options.length; i++) {
		var o = options[i];
		text += '<option value="' + afcHelper_escapeHtmlChars(o.value) + '" ';
		if (o.selected) text += 'selected="selected" ';
		if (o.disabled) text += 'disabled ';
		text += '>' + o.label + '</option>';
	}
	text += "</select>";
	return text;
}

function afcHelper_generateChzn(title,placeholder,optionsdict) {
	// given a dictionary of "title","value"
	var text = '<select data-placeholder="' + placeholder + '" id="' + title + '" style="width:350px;" class="chzn-select" multiple>';
	$.each(optionsdict, function(k, v){
		text += '<option value="' + afcHelper_escapeHtmlChars(v) + '" >' + k + '</option>';
	});
	text += "</select>";
	return text;
}

function afcHelper_escapeHtmlChars(original) {
	return original.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
}

function afcHelper_countString(str, search, casesensitive){
	// Returns count of occurances of a "search" string in "str"
	// Casesensitive can be set to true for case sensitive matching
	if (!casesensitive) str = str.toLowerCase();
	var count = 0;
	var index = str.indexOf(search);
	while(index !=- 1){
		count++;
		index = str.indexOf(search,index+1);
	}
	return count;
}

function afcHelper_getPageText(title, show, redirectcheck, timestamp) {
	if (show) $('#afcHelper_status').html($('#afcHelper_status').html() + '<li id="afcHelper_get' + jqEsc(title) + '">प्राप्त गर्दै <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a></li>');

	var request = {
				'action': 'query',
				'prop': 'revisions',
				'rvprop': 'content',
				'format': 'json',
				'indexpageids': true,
				'titles' : title
			};
	if (redirectcheck) request.redirects = true;
	if (timestamp) request.rvprop = 'content|timestamp';

	var response = JSON.parse(
		$.ajax({
			url: mw.util.wikiScript('api'),
			data: request,
			async: false
		})
		.responseText
	);

	pageid = response['query']['pageids'][0];
	if (pageid === "-1") {
		if (show) $('#afcHelper_get' +jqEsc(title)).html('पृष्ठ <a class="new" href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a> अवस्थित छैन');
		return '';
	}
	var newtext = response['query']['pages'][pageid]['revisions'][0]['*'];
	if (redirectcheck && response['query']['redirects'] /* If &redirects if specified but there is no redirect, this stops us from getting an error */){
		var oldusername = response['query']['redirects'][0]['from'];
		var newusername = response['query']['redirects'][0]['to'];
		if ((typeof(oldusername) !== 'undefined') && (typeof(newusername) !== 'undefined') && (oldusername != newusername)){
			usertalkpage = newusername;
			if (show) {
				$('#afcHelper_status').html($('#afcHelper_status').html() + '<li id="afcHelper_get' + jqEsc(title) + '">पाइयो <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + newusername + '">' + newusername + '</a> (पृष्ठ पुन: नामाकरण गरिएको थियो ' + oldusername + ')</li>');
			}
		} else {
			redirectcheck = false;
		}
	} else {
			redirectcheck = false;
	}		
	if (show && !redirectcheck)	$('#afcHelper_status').html($('#afcHelper_status').html() + '<li id="afcHelper_get' + jqEsc(title) + '">पाइयो <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a></li>');
	if (!timestamp) return newtext;
	else return {'pagetext':newtext,'timestamp':response['query']['pages'][pageid]['revisions'][0]['timestamp']};
}

function afcHelper_deletePage(title,reason) {
	// First set up the status log
	$("#afcHelper_finished_wrapper").html('<span id="afcHelper_AJAX_finished_' + afcHelper_AJAXnumber + '" style="display:none">' + $("#afcHelper_finished_wrapper").html() + '</span>');
	var func_id = afcHelper_AJAXnumber;
	afcHelper_AJAXnumber++;
	document.getElementById('afcHelper_status').innerHTML += '<li id="afcHelper_delete' + escape(title) + '">मेटाउँदै <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a></li>';

	// Then get the deletion token
	var tokenrequest = {
		'action': 'query',
		'prop': 'info',
		'format': 'json',
		'intoken': 'delete',
		'indexpageids': true,
		'titles': title
	};
	var tokenresponse = JSON.parse(
		$.ajax({
			url: mw.util.wikiScript('api'),
			data: tokenrequest,
			async: false
		})
		.responseText
	);

	pageid = tokenresponse['query']['pageids'][0];
	token = tokenresponse['query']['pages'][pageid]['deletetoken'];

	// And finally delete the page
	var delrequest = {
				'action': 'delete',
				'reason': reason + afcHelper_advert,
				'format': 'json',
				'token': token,
				'title': title
			}
	var delresponse = JSON.parse(
		$.ajax({
			type: "POST",
			url: mw.util.wikiScript('api'),
			data: delrequest,
			async: false
		})
		.responseText
	);

	if (delresponse && delresponse.delete) {
		$('#afcHelper_delete' + jqEsc(title)).html('मेटाइयो <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a>');
		return true;
	} else {
		$('#afcHelper_delete' + jqEsc(title)).html('<div style="color:red"><b>Deletion failed on <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a></b></div>. त्रुटि जानकारी: ' + JSON.stringify(delresponse));
		window.console && console.error('मेटाउने कार्य असफल भयो %s (%s). त्रुटि जानकारी: %s', mw.config.get('wgArticlePath').replace("$1", encodeURI(title)), title, JSON.stringify(delresponse));
		return false;
	}
}

function afcHelper_editPage(title, newtext, summary, createonly, nopatrol) {
	var edittoken = mw.user.tokens.get('csrfToken');
	summary += afcHelper_advert;
	$("#afcHelper_finished_wrapper").html('<span id="afcHelper_AJAX_finished_' + afcHelper_AJAXnumber + '" style="display:none">' + $("#afcHelper_finished_wrapper").html() + '</span>');
	var func_id = afcHelper_AJAXnumber;
	afcHelper_AJAXnumber++;
	$('#afcHelper_status').html($('#afcHelper_status').html() + '<li id="afcHelper_edit' + jqEsc(title) + '">सम्पादन गर्दै <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a></li>');
	var request = {
				'action': 'edit',
				'title': title,
				'text': newtext,
				'summary': summary,
				'token': edittoken
		};
	if (createonly) request.createonly = true;

	var api = new mw.Api();
	api.post(request)
			.done(function ( data ) {
				if ( data && data.edit && data.edit.result && data.edit.result == 'Success' ) {
					$('#afcHelper_edit' + jqEsc(title)).html('प्रकाशित <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a>');
				} else {
					$('#afcHelper_edit' + jqEsc(title)).html('<span class="afcHelper_notice"><b>सम्पादन असफल <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a></b></span>. त्रुटि जानकारी: ' + JSON.stringify(data));
					window.console && console.error('सम्पादन असफल %s (%s). त्रुटि जानकारी: %s', mw.config.get('wgArticlePath').replace("$1", encodeURI(title)), title, JSON.stringify(data));
				}
			} )
			.fail( function ( error ) {
				if (createonly && error == "articleexists")
					$('#afcHelper_edit' + jqEsc(title)).html('<span class="afcHelper_notice"><b>सम्पादन असफल <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a></b></span>. त्रुटि जानकारी: लेख पहिले नै अवस्थित छ!');
				else
					$('#afcHelper_edit' + jqEsc(title)).html('<span class="afcHelper_notice"><b>सम्पादन असफल <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a></b></span>. त्रुटि जानकारी: ' + error); 
			})
			.always( function () {
				$("#afcHelper_AJAX_finished_" + func_id).css("display", '');
			});

	if (!nopatrol) {
		/* We patrol by default */
		if ($('.patrollink').length) {
			// Extract the rcid token from the "Mark page as patrolled" link on page
			var patrolhref = $('.patrollink a').attr('href');
			var rcid = mw.util.getParamValue('rcid', patrolhref);

			if (rcid) {
				$('#afcHelper_status').html($('#afcHelper_status').html() + '<li id="afcHelper_patrol' + jqEsc(title) + '">चिह्नित गर्दै <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + ' गस्ती गरिएको</a></li>');
				var patrolrequest = {
							'action': 'patrol',
							'format': 'json',
							'token': mw.user.tokens.get('patrolToken'),
							'rcid': rcid
					};
				api.post(patrolrequest)
						.done(function ( data ) {
							if ( data ) {
								$('#afcHelper_patrol' + jqEsc(title)).html('चिह्नित <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a> गस्ती भएको');
							} else {
								$('#afcHelper_patrol' + jqEsc(title)).html('<span class="afcHelper_notice"><b>गस्ती असफल <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a></b></span> एक अज्ञात त्रुटिको साथ');
								window.console && console.error('एक अज्ञात त्रुटिको साथ %s (%s) गस्ती असफल भयो।', mw.config.get('wgArticlePath').replace("$1", encodeURI(title)), title);
							}
						} )
						.fail( function ( error ) {
							$('#afcHelper_patrol' + jqEsc(title)).html('<span class="afcHelper_notice"><b>गस्ती असफल <a href="' + mw.config.get('wgArticlePath').replace("$1", encodeURI(title)) + '" title="' + title + '">' + title + '</a></b></span>. त्रुटि जानकारी: ' + error); 
						});
			}				
		}
	}
}

function afcHelper_cleanuplinks(text) {
	// Convert external links to Wikipedia articles to proper wikilinks
	var wikilink_re = /(\[){1,2}(?:https?:)?\/\/(ne.wikipedia.org\/wiki|newp.org)\/([^\s\|\]\[]+)(\s|\|)?((?:\[\[[^\[\]]*\]\]|[^\]\[])*)(\]){1,2}/gi;
	var temptext = text;
	var match;
	while (match = wikilink_re.exec(temptext)) {
		var pagename = decodeURI(match[3].replace(/_/g,' '));
		var displayname = decodeURI(match[5].replace(/_/g,' '));
		if (pagename === displayname) displayname = '';
		var replacetext = '[[' + pagename + ((displayname) ? '|' + displayname : '') + ']]';
		pagetext = pagetext.replace(match[0],replacetext);
	}
	return text;
}
// Patch for WPAFC/afch that prevents non-whitelisted
// users from using the *old* helper script.
( function ( $, mw ) {
	mw.loader.using( [ 'mediawiki.api' ], function () {
		var whitelistTitle = 'विकिपिडिया:विकिपरियोजना लेख सृजना/सहभागीहरू';

		function showNotListedError ( user ) {
			mw.notify(
				$( '<div>' )
					.append( 'लेसृसा लोड गर्न सकिएन किनकि "' + user + '" सूचीकृत छैन ' )
					.append(
						$( '<a>' )
							.attr( 'href', mw.util.getUrl( whitelistTitle ) )
							.attr( 'title', whitelistTitle )
							.text( whitelistTitle )
							.attr( 'target', '_blank' )
					)
					.append( '. तपाईं त्यहाँ लेसृ सहायक स्क्रिप्ट पहुँच अनुरोध गर्न सक्नुहुन्छ।' ),
				{
					title: 'लेसृसा त्रुटि: प्रयोगकर्ता सूचीबद्ध छैन',
					autoHide: false
				}
			);
		}

		function destroyOldAfch () {
			// Remove review link
			$( '#ca-afcHelper' ).remove();

			// Old script used displayMessage; just destroy its div.
			// Hopefully no other scripts used it... ^.^
			$( '#display-message' ).remove();

			// Remove all afc-ish divs
			$( 'div[id^="afcHelper_"]' ).remove();

			// Disable the global init functions
			window.afcHelper_init = function () { return false; };
			window.afcHelper_redirect_init  = function () { return false; };
			window.afcHelper_ffu_init  = function () { return false; };
		}

		function getText ( pageTitle ) {
			var deferred = $.Deferred();

			// Use afch-rewrite `AFCH.Page` if possible to utilize cache
			if ( window.AFCH ) {
				return ( new AFCH.Page( pageTitle ) ).getText( true );
			}

			// Otherwise just peform the API request ourselves
			new mw.Api().get( {
				action: 'query',
				prop: 'revisions',
				rvprop: 'content',
				indexpageids: true,
				titles:  pageTitle
			} ).done( function ( data ) {
				var id = data.query.pageids[0];
				deferred.resolve( data.query.pages[id].revisions[0]['*'] );
			} );

			return deferred;
		}

		function checkWhitelist () {
			getText( whitelistTitle ).done( function ( text ) {
				var userName = mw.user.id(),
					userAllowed = text.indexOf( userName ) !== -1;

				if ( !userAllowed ) {
					destroyOldAfch();

					// Show the error message. If afch-rewrite is installed,
					// don't show the error message twice.
					if ( !window.AFCH ) {
						showNotListedError( userName );
					}
				}
			} );
		}

		checkWhitelist();
	} );
}( jQuery, mediaWiki ) );

//</nowiki>