MediaWiki:Gadget-Adiutor-AIV.js

From wikishia

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.
/* Adiutor: Adiutor enables versatile editing options and modules to assist a variety of user actions to enhance the Wikipedia editing experience. */
/* Author: Vikipolimer */
/* Learn more at: https://meta.wikimedia.org/wiki/Adiutor */
/* Licensing and Attribution: Licensed under Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) */
/* Module: Administrator intervention against vandalism */
/* <nowiki> */
// Get essential configuration from MediaWiki
var mwConfig = mw.config.get(["skin", "wgAction", "wgArticleId", "wgPageName", "wgNamespaceNumber", "wgTitle", "wgUserGroups", "wgUserName", "wgUserEditCount", "wgUserRegistration", "wgCanonicalNamespace"]);
var api = new mw.Api();
var wikiId = mw.config.get("wgWikiID");
var adiutorUserOptions = JSON.parse(mw.user.options.get("userjs-adiutor-" + wikiId));
var rationaleInput, VandalizedPageInput, reportType, sockPuppetsList, sockpuppetryType, revId, updatedContent;
var VandalizedPage = {};
VandalizedPage.value = null;
var revisionID = {};
revisionID.value = null;
var sockpuppeteerInput;
api.get({
	action: "query",
	prop: "revisions",
	titles: "MediaWiki:Gadget-Adiutor.json",
	rvprop: "content",
	formatversion: 2
}).done(function(data) {
	var content = data.query.pages[0].revisions[0].content;
	var jsonData = JSON.parse(content);
	var reportRationales = jsonData[2].adiutorReportRationales;
	console.log(reportRationales);

	function AivDialog(config) {
		AivDialog.super.call(this, config);
	}
	OO.inheritClass(AivDialog, OO.ui.ProcessDialog);
	AivDialog.static.name = "AivDialog";
	AivDialog.static.title = new OO.ui.deferMsg("aiv-module-title");
	AivDialog.static.actions = [{
		action: "save",
		label: new OO.ui.deferMsg("report"),
		flags: ["primary", "progressive"]
	}, {
		label: new OO.ui.deferMsg("cancel"),
		flags: "safe"
	}];
	AivDialog.prototype.initialize = function() {
		AivDialog.super.prototype.initialize.apply(this, arguments);
		var headerTitle = new OO.ui.MessageWidget({
			type: "notice",
			inline: true,
			label: new OO.ui.deferMsg("aiv-header-title")
		});
		var headerTitleDescription = new OO.ui.LabelWidget({
			label: new OO.ui.deferMsg("aiv-header-description")
		});
		// Add margin-top to headerTitleDescription
		headerTitleDescription.$element.css({
			"margin-top": "20px",
			"font-weight": "300"
		});
		var RationaleSelector = new OO.ui.DropdownWidget({
			menu: {
				items: [
					new OO.ui.MenuOptionWidget({
						data: 1,
						label: new OO.ui.deferMsg("vandalism")
					}),
					new OO.ui.MenuOptionWidget({
						data: 2,
						label: new OO.ui.deferMsg("username-violation")
					}),
					new OO.ui.MenuOptionWidget({
						data: 3,
						label: new OO.ui.deferMsg("sockpuppeteer")
					}),
					new OO.ui.MenuOptionWidget({
						data: 4,
						label: new OO.ui.deferMsg("sockpuppet")
					})
				]
			},
			label: new OO.ui.deferMsg("report-type")
		});
		// Add margin-top to RationaleSelector
		RationaleSelector.$element.css("margin-top", "20px");
		this.content = new OO.ui.PanelLayout({
			padded: true,
			expanded: false
		});
		var RequestRationaleContainer = new OO.ui.FieldsetLayout({
			classes: ["adiutor-report-window-rationale-window"]
		});
		RequestRationaleContainer.$element.css("margin-top", "20px");
		RationaleSelector.getMenu().on("choose", function(menuOption) {
			switch(menuOption.getData()) {
				case 1:
					RequestRationale = new OO.ui.FieldsetLayout({
						label: mw.msg('rationale')
					});
					var generalRationales = reportRationales.filter(function(item) {
						return item.related === "general";
					});
					RequestRationale.addItems([
						new OO.ui.FieldLayout(VandalizedPage = new OO.ui.TextInputWidget({
							value: ""
						}), {
							label: new OO.ui.deferMsg("related-page"),
							help: new OO.ui.deferMsg("related-page-description")
						}),
						new OO.ui.FieldLayout(revisionID = new OO.ui.TextInputWidget({
							value: ""
						}), {
							label: new OO.ui.deferMsg("revision-id"),
							help: new OO.ui.deferMsg("revision-id-description")
						}),
					]);
					generalRationales.forEach(function(rationaleItem) {
						RequestRationale.addItems([
							new OO.ui.FieldLayout(new OO.ui.CheckboxInputWidget({
								selected: false,
								data: rationaleItem.data
							}), {
								label: rationaleItem.label,
								align: "inline"
							}),
						]);
					});
					reportType = "regularReport";
					break;
				case 2:
					RequestRationale = new OO.ui.FieldsetLayout({
						label: mw.msg('rationale')
					});
					// Burada, reportRationales setinden gelen ve related değeri username olan öğeleri filtreleyerek yeni bir dizi oluşturuyoruz.
					var usernameRationales = reportRationales.filter(function(item) {
						return item.related === "username";
					});
					// Şimdi bu usernameRationales dizisini kullanarak RequestRationale'a öğeleri ekleyebiliriz.
					usernameRationales.forEach(function(rationaleItem) {
						RequestRationale.addItems([
							new OO.ui.FieldLayout(new OO.ui.CheckboxInputWidget({
								selected: false,
								data: rationaleItem.data
							}), {
								label: rationaleItem.label,
								align: "inline"
							}),
						]);
					});
					reportType = "regularReport";
					break;
				case 3:
					RequestRationale = new OO.ui.FieldsetLayout({
						label: mw.msg("report-suspected-sockpuppeteer")
					});
					RequestRationale.addItems([
						new OO.ui.MessageWidget({
							type: "warning",
							inline: true,
							label: mw.msg("sockpuppetry-warning-text")
						}),
						new OO.ui.FieldLayout(sockPuppetsList = new OO.ui.TagMultiselectWidget({
							placeholder: mw.msg("sockpuppets-input-placeholder"),
							allowArbitrary: true
						})),
						new OO.ui.FieldLayout(evidenceTextInput = new OO.ui.MultilineTextInputWidget({
							placeholder: mw.msg('evidence-input-placeholder'),
							value: "",
							indicator: "required"
						}), {
							label: mw.msg('evidence'),
							align: "inline"
						}),
					]);
					reportType = "sockpuppetry";
					sockpuppetryType = "sockpuppeteer";
					break;
				case 4:
					RequestRationale = new OO.ui.FieldsetLayout({
						label: mw.msg("report-suspected-sockpuppet")
					});
					RequestRationale.addItems([
						new OO.ui.MessageWidget({
							type: "warning",
							inline: true,
							label: mw.msg("sockpuppetry-warning-text")
						}),
						new OO.ui.FieldLayout(sockpuppeteerInput = new OO.ui.TextInputWidget({
							value: "",
							indicator: "required"
						}), {
							label: mw.msg('sockpuppeteer'),
							help: mw.msg('sockpuppeteer-help-text')
						}),
						new OO.ui.FieldLayout(evidenceTextInput = new OO.ui.MultilineTextInputWidget({
							placeholder: mw.msg('evidence-input-placeholder'),
							value: "",
							indicator: "required"
						}), {
							label: mw.msg('evidence'),
							align: "inline"
						}),
					]);
					reportType = "sockpuppetry";
					sockpuppetryType = "sockpuppet";
					break;
			}
			console.log(reportType);
			RequestRationaleContainer.$element.html(RequestRationale.$element);
			windowManager.onWindowResize();
		});
		this.content.$element.append(headerTitle.$element, headerTitleDescription.$element, RationaleSelector.$element, RequestRationaleContainer.$element);
		this.$body.append(this.content.$element);
	};
	AivDialog.prototype.getActionProcess = function(action) {
		if(action) {
			switch(reportType) {
				case "sockpuppetry":
					switch(sockpuppetryType) {
						case "sockpuppeteer":
							var selectedValues = sockPuppetsList.getValue();
							var sockpuppets = selectedValues.map(function(value) {
								return "\n* {{checkuser|" + value + "}}";
							});
							var formattedSockpuppets = sockpuppets.join("");
							preparedText = "{{subst:please don't edit this line (new rfcu case)}}\n* {{checkuser|" + getFormattedPageName() + "}}\n==== Suspected related users ====" + formattedSockpuppets + "\n==== Rationale, discussion and results ====\n'''Reason:''' " + evidenceTextInput.value + " ~~~~";
							postSockpuppetRequest(getFormattedPageName());
							break;
						case "sockpuppet":
							preparedText = "{{subst:please don't edit this line (new rfcu case)}}\n* {{checkuser|" + sockpuppeteerInput.value + "}}\n==== Suspected related users ====\n* {{checkuser|" + getFormattedPageName() + "}}\n==== Rationale, discussion and results ====\n'''Reason:''' " + evidenceTextInput.value + " ~~~~";
							postSockpuppetRequest(sockpuppeteerInput.value);
							break;
					}
					break;
				case "regularReport":
					if(RequestRationale) {
						var rationaleInput = findSelectedRationale();
						if(rationaleInput) {
							var VandalizedPageInput = VandalizedPage.value ? " on the [[" + VandalizedPage.value + "]] page." : "";
							var revId = revisionID.value ? "([[Special:Diff/" + revisionID.value + "|diff]]) " : "";
							preparedText = '{{user3|' + mwConfig.wgPageName.replace(/_/g, " ").replace('User:', '').replace('Special:Contributions/', '') + '}}\n' + rationaleInput + VandalizedPageInput + revId + ' ~~~~';
							postRegularReport();
						} else {
							OO.ui.alert(new OO.ui.deferMsg("select-rationale")).done(function() {});
						}
					}
					break;
			}
		}
		return AivDialog.super.prototype.getActionProcess.call(this, action);
	};

	function getFormattedPageName() {
		return mwConfig.wgPageName.replace(/_/g, " ").replace("User:", "").replace("User talk:", "").replace("Special:Contributions/", "");
	}

	function postSockpuppetRequest(sockpuppeteer) {
		api.postWithToken("csrf", {
			action: "edit",
			title: "Commons:Requests for checkuser/Case/" + sockpuppeteer,
			appendtext: "\n" + preparedText + "\n",
			Summary: "Created case for [[User:" + sockpuppeteer + "]].",
			tags: "Adiutor",
			format: "json"
		}).done(function() {
			// After successfully posting the request for the individual case,
			// we want to add a link to this case on the "Commons:Requests for checkuser" page.
			// Get the current content of the "Commons:Requests for checkuser" page.
			api.get({
				action: "query",
				prop: "revisions",
				titles: "Commons:Requests for checkuser",
				rvprop: "content",
				formatversion: 2
			}).done(function(data) {
				var currentPageContent = data.query.pages[0].revisions[0].content;
				var caseLink = "{{Commons:Requests for checkuser/Case/" + sockpuppeteer + "}}";
				// Check if the case link already exists in the content.
				if(currentPageContent.includes(caseLink)) {
					console.log("The case link already exists.");
					return;
				}
				// Find the position of the first occurrence of a similar pattern.
				var pattern = /\{\{Commons:Requests for checkuser\/Case\/[^\}]+\}\}/;
				var match = pattern.exec(currentPageContent);
				if(match) {
					// Insert the case link just above the first occurrence of a similar pattern.
					var index = match.index;
					updatedContent = currentPageContent.slice(0, index) + caseLink + "\n" + currentPageContent.slice(index);
				} else {
					// If there is no similar pattern, add the case link to the end of the content.
					updatedContent = currentPageContent + caseLink;
				}
				// Now, update the "Commons:Requests for checkuser" page with the updated content.
				api.postWithToken("csrf", {
					action: "edit",
					title: "Commons:Requests for checkuser",
					text: updatedContent,
					Summary: "[[Commons:Requests for checkuser/Case/" + sockpuppeteer + "|Case]] added.",
					tags: "Adiutor",
					format: "json"
				}).done(function() {
					console.log("Successfully added the case link.");
					window.location = "/commons/Commons:Requests for checkuser/Case/" + sockpuppeteer;
				});
			});
		});
	}

	function findSelectedRationale() {
		var rationaleInput = null;
		RequestRationale.items.forEach(function(Rationale) {
			if(Rationale.fieldWidget.selected) {
				rationaleInput = Rationale.fieldWidget.data;
			}
		});
		return rationaleInput;
	}

	function postRegularReport() {
		api.postWithToken("csrf", {
			action: "edit",
			title: 'Commons:Administrators\' noticeboard/Blocks and protections',
			section: 'new',
			sectiontitle: 'Block request for [[User:' + mwConfig.wgPageName.replace(/_/g, " ").replace('User:', '').replace('Special:Contributions/', '') + ']]',
			appendtext: "\n" + preparedText + "\n",
			summary: '[[User:' + mwConfig.wgPageName.replace(/_/g, " ").replace('User:', '').replace('Special:Contributions/', '') + ']] has been reported.',
			tags: "Adiutor",
			format: "json"
		}).done(function() {
			adiutorUserOptions.stats.blockRequests++;
			api.postWithEditToken({
				action: "globalpreferences",
				format: "json",
				optionname: "userjs-adiutor",
				optionvalue: JSON.stringify(adiutorUserOptions),
				formatversion: 2
			}).done(function() {});
			window.location = '/commons/Commons:Administrators%27_noticeboard/Blocks_and_protections';
		});
	}
	var windowManager = new OO.ui.WindowManager();
	$(document.body).append(windowManager.$element);
	var dialog = new AivDialog();
	windowManager.addWindows([dialog]);
	windowManager.openWindow(dialog);
});
/* </nowiki> */