Jump to content

User:DannyS712 test/PC bot.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
//<nowiki>
$(function (){
var PC_bot_config = {
	name: '[[User:DannyS712/PC bot|PC bot]]',
	version: '1.8.1',
	debug: false
};

var PC_bot_advert = "Task 11: Disable the categories on this page while it is still a draft, per [[WP:USERNOCAT]], using " + PC_bot_config.name + " (v. " + PC_bot_config.version + ")";

var root_user_pages = [];
var will_fix = [];
var unable_to_fix = [];

mw.loader.using( 'mediawiki.util', function () {
    $(document).ready( function () {
    	importScript( 'User:DannyS712 test/page.js' );
		if ( mw.config.get( 'wgPageName' ) === "Wikipedia:Database_reports/Polluted_categories") {
		    $(document).ready( function () { 
		    	mw.util.addPortletLink ( 'p-cactions', 'javascript:void(0)', 'Polluted categories', 'ca-polluted', 'TOOLTIP');
		    	$('#ca-polluted').on('click', function() {
		        	Polluted_categories();
		    	} );
		    } );
		}
    } );
} );
function PC_bot ( category_name ) {
	return new Promise((resolve) => {
		console.log( '\t', category_name );
		var getDrafts = {
	        action: 'query',
	        list: 'categorymembers',
	        cmlimit: 'max',
	        cmtitle: category_name,
	        cmprop: 'title',
	        format: 'json'
		};
		$.get( mw.config.get( 'wgScriptPath' ) + '/api.php', getDrafts, function( Drafts ) {
			//console.log(Drafts);
			var pages = Drafts.query.categorymembers;
			for (var i = 0; i < pages.length; i++) {
				if (pages[i].ns === 2){
					var name = pages[i].title;
					//console.log("Page:", name);
					if ( name.indexOf('/') > -1 ){
						console.log("Will try:", name);
						will_fix.push( name );
						//draft_no_cat( name );
					} else {
						console.log( "Root user page:", name);
						root_user_pages.push( '* [[' + name + ']]' );
					}
				}
			}
			//location.reload();
			resolve();
		} );
	} );
}
async function Polluted_categories(){
	var content1 = get_page( mw.config.get( 'wgPageName' ) );
	if (PC_bot_config.debug) console.log( content1 );
	var content2 = content1.replace( /\|-\n\| (\d*)\n\| {{dbr link\|1=(.*)}}/g, '"$2",');
	if (PC_bot_config.debug) console.log( content2 );
	var content3 = content2.replace( /(.*\n)*! Category\n/i, '{\n"Pages": [');
	if (PC_bot_config.debug) console.log( content3 );
	var content4 = content3.replace ( /,\n\|}/, "\n] }");
	if (PC_bot_config.debug) console.log( content3 );
	var content5 = content4.replace ( /_/g, " ");
	if (PC_bot_config.debug) console.log( content5 );
	var as_JSON = JSON.parse( content5 );
	if (PC_bot_config.debug) console.log( as_JSON );
	var array = as_JSON.Pages;
	console.log( array );
	
	var page = "";
	for (var iii = 0; iii < array.length; iii++){
		page = 'Category:' + array[iii];
		if (/AfC submissions.*/.test(page)) console.log( "Skip: AfC" );
		else if (/.*Wikipedians/.test(page)) console.log( "Skip: Wikipedians");
		else if (/Wikipedia.*/.test(page)) console.log( "Skip: Wikipedia");
		else if (/WikiProject.*/.test(page)) console.log( "Skip: WikiProject");
		else if (/.*ArtAndFeminism.*/.test(page)) console.log( "Skip: ArtAndFeminism");
		else if (/.*User pages.*/.test(page)) console.log( "Skip: User page");
		else if (/.*Portal templates.*/.test(page)) console.log( "Skip: Portal templates");
		
		else {
			await PC_bot( page );
		}
	}
	var to_try = [...new Set(will_fix)];
	//console.log( to_try );
	for (var jjj = 0; jjj < to_try.length; jjj++){
		await draft_no_cat(to_try[jjj]);
	}
	//console.log("Unable to fix:", unable_to_fix);
	
	var unique_root_user_pages = [...new Set(root_user_pages)];
	//console.log( "Root user pages skipped:", unique_root_user_pages );
	var requestContent = 'DannyS712 bot needs help with task 11 (polluted categories); the following pages appear to be categorized as articles, but weren\'t automatically fixed because they are root user pages:\n\n{{div col}}\n';
	requestContent = requestContent + unique_root_user_pages.join('\n') + '\n\n{{div col end}}\n\n';
	requestContent = requestContent + 'Additionally, the following pages appear to be categorized as articles through the transclusion of templates, and so I couldn\'t fix them.\n\n{{div col}}\n';
	requestContent = requestContent + unable_to_fix.join('\n') + '\n\n{{div col end}}\n\nThanks, --~~~~';
	console.log(requestContent);
	var sectionHeading = 'Task 11: Help needed, {{subst:#time: Y-m-d }}';
	var requestSummary = 'DannyS712 bot needs help - requested using ' + PC_bot_config.name + " (v. " + PC_bot_config.version + ")";
	//botNeedsHelp(requestSummary, sectionHeading, requestContent);
}
function draft_no_cat( title ){
	return new Promise((resolve) => {
		var send_req = {
		    action: 'query',
		    titles: title,
		    prop: 'revisions',
		    intoken: 'edit',
		    rvprop: 'content',
		    indexpageids: 1,
		    dataType: 'xml',
		    format: 'xml'
		};
		$.get( mw.config.get( 'wgScriptPath' ) + '/api.php', send_req, function( response ) {
		    var text = $( response ).find( 'rev' ).text();
		    var new_text = text.replace( /\[\[Category/gi, '\[\[:Category' ); // Replace categorization with links
		    var submit = {
		        action: 'edit',
		        title: title,
		        text: new_text,
		        summary: PC_bot_advert,
		        minor: true,
		        bot: true,
		        token: mw.user.tokens.get( 'csrfToken' )
		    };
		    if ( text === new_text ) {
		    	console.log('Unable to fix: ' + title);
		    	unable_to_fix.push( '* [[' + title + ']]' );
		    } else {
			    $.when(
			        $.post( mw.config.get( 'wgScriptPath' ) + '/api.php', submit, function( response ){ } )
			    ).done( function() {
			    	console.log("Done: " + title);
			    } );
	    	}
	    	resolve();
		} );
	} );
}
function botNeedsHelp( summary, title, content) {
    $.ajax({
        url: mw.util.wikiScript( 'api' ),
        data: {
            format: 'json',
            action: 'edit',
            title: 'User talk:DannyS712 bot',
            section: 'new',
            sectiontitle: title,
            summary: summary,
            text: content,
            token: mw.user.tokens.get( 'csrfToken' )
        },
        dataType: 'json',
        type: 'POST',
        success: function( data ) {
            if ( data && data.edit && data.edit.result == 'Success' ) {
                console.log( 'Help requested' ); // reload page if edit was successful
            } else if ( data && data.error ) {
                alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info );
            } else {
                alert( 'Error: Unknown result from API.' );
            }
        },
        error: function( xhr ) {
            alert( 'Error: Request failed.' );
        }
    });
}
});
//</nowiki>