User:Dessamator/js/MassCategorization/code.js

/*
 * Mass Categorization
 * @description (De)Categorize listed multiple pages.
 * @author Ozuzanna
 * @TODO fix replace
 * Added option for (Dessamator)


 * (function($, mw) {

if ($('#t-mc').length) return;

// Replace \

var FormMC = '\  \ \          Mode: \  \ Add \ Remove \ \          \           Category: \  \ Matching: \ \              General (does not account for piped categories) \ \              Broad (also match possible further characters of the specified category e.g. Foo and Foo123, but takes care of pipes) \ \          \               Include in transclusion (for templates) \ \          \           Put the name of each page you want to categorize on a separate line. \               \ \      Any errors encountered will appear below  \ ',   delay = window.massCategorizationDelay || 1000;

//Support for Monobook if (mw.config.get('skin') === 'monobook') { mw.util.addPortletLink('p-tb', '#', 'Mass Categorization', 't-mc'); } else { $('#my-tools-menu').prepend(' Mass Categorization'); }

document.getElementById('t-mc').addEventListener('click', function {        $.showCustomModal('Mass Categorization', FormMC, { id: 'form-categorization', width: 500, buttons: [{ message: 'Cancel', handler: function { $('#form-categorization').closeModal; }           }, {                message: 'Add category contents', defaultButton: true, handler: function { addCategoryContents; }           }, {                id: 'start-button', message: 'Initiate', defaultButton: true, handler: function { init; }           }]        });    });

function addCategoryContents { var category = prompt('Please enter the category name (no category prefix):').replace('_',' '); new mw.Api.get({           action: 'query',            list: 'categorymembers',            cmtitle: "Category:"+category,            cmlimit: 5000        }) .done(function(d) {           if (!d.error) {                var data = d.query;                if (data.categorymembers) {                    for (var i in data.categorymembers) {                        $('#text-categorization').append(data.categorymembers[i].title+'\n');                    }                }                else {                    $('#text-error-output').append(category + ' does not exist!\n');                }            }            else {                $('#text-error-output').append('Failed to get contents of '+ category +' : '+ d.error.code +' ');            }        }) .fail(function {           $('#text-error-output').append('Failed to get contents of '+ category +'! ');       });    }

function init { var catName = document.getElementById('category-name').value, txt = document.getElementById('text-categorization'), pages = txt.value.split('\n'), page = pages[0];

if (!catName) { alert('Please enter the category name!'); return; }

document.getElementById('start-button').setAttribute('disabled','disabled');

if (!page) { document.getElementById('start-button').removeAttribute("disabled"); $.showCustomModal('Finished!', 'Nothing left to do, or next line is blank.', {               id: 'form-complete',                width: 200,                buttons: [{                    message: 'Close',                    defaultButton: true,                    handler: function {                        $('#form-complete').closeModal;                    }                }]            }); }        else { categorize(page,catName); }       pages = pages.slice(1,pages.length); txt.value = pages.join('\n'); }

function categorize(pageToCat,cat) { var actionVal = $('#select-mc').val; if (actionVal == 1) { //add category new mw.Api.get({               format: 'json',                action: 'query',                titles: pageToCat,                prop: 'categories'            }) .done(function(d) {               var pages = d.query.pages;                    for (var page in pages) {                    var mPage = pages[page],                        knownCats = [];                    if (mPage.categories) {                        for (var i = 0; i < mPage.categories.length; i++) {                            knownCats.push(mPage.categories[i].title);                        }                    }                }                cat = 'Category:'+ cat.charAt(0).toUpperCase + cat.substring(1);                if (knownCats.indexOf(cat) === -1 || knownCats === 'undefined') {                    var sPrefix="";                    var sSuffix = "";                    if ($('input[name=mass-categorization-noinclude]').prop('checked')){                        sPrefix =" ";                        sSuffix = "<\/noinclude>";                    }                    var config = { format: 'json', action: 'edit', title: pageToCat, summary: 'Adding category ['+'['+cat+'|'+cat.substring(9)+']] (automatic)', nocreate: '', appendtext: sPrefix + '\n['+'['+cat+']]'+ sSuffix, bot: true, token: mw.user.tokens.get('editToken') };

if (mw.config.get("wgUserGroups").join(' ').indexOf('bot') == -1) delete config.bot;

$.ajax({                       url: mw.util.wikiScript('api'),                        data: config,                        dataType: 'json',                        type: 'POST',                        success: function(d) {                            if (!d.error) {                                console.log('Category successfully added to '+pageToCat+'!');                            }                             else {                                console.log('Failed to add category to '+pageToCat+': '+ d.error.code);                                $('#text-error-output').append('Failed to add category to '+pageToCat+': '+ d.error.code +' ');                            }                        },                        error: function {                            console.log('Failed to add category to '+pageToCat+'!');                            $('#text-error-output').append('Failed to add category to '+pageToCat+'! ');                       }                    });                }                else { console.log(pageToCat+ ' already has the category '+cat.substring(9)+' or an error was encountered. '+pageToCat+' has been skipped.'); $('#text-error-output').append(pageToCat+ ' already has the category '+cat.substring(9)+' or an error was encountered. '+pageToCat+' has been skipped. '); }           })            .fail(function { console.log('Category check failed for '+pageToCat+'! It has been skipped.'); $('#text-error-output').append('Category check failed for '+pageToCat+'! It has been skipped. '); });       }

if (actionVal == 2) { //remove category

//get page contents new mw.Api.get({               action: 'query',                prop: 'revisions',                rvprop: 'content',                titles: pageToCat            }) .done(function(d) {               if (!d.error) {                    for (var i in d.query.pages) {                        if (d.query.pages[i].revisions) {                            var content = d.query.pages[i].revisions[0]["*"];                        }                        else {                            $('#text-error-output').append('Page '+pageToCat+' does not exist! ');                           return;                        }                    }

//remove old category var regex = new RegExp ("\\[\\[Category:"+cat+"\\]\\]","gi"); var sRegEx = "\\[\\[Category:"+cat+"\\|?.*?\\]\\]"; if ($('input[name=mass-categorization-removal]:checked').val == 2){ regex = new RegExp (sRegEx,"gi"); }                   if ($('input[name=mass-categorization-noinclude]').prop('checked')){ regex = new RegExp ("\\\\s*"+sRegEx+"\\s*\\<\/noinclude\\>","gi"); }                   var changedContent = content.replace(regex,''); cat = 'Category:'+ cat.charAt(0).toUpperCase + cat.substring(1);

//don't submit if new and old contents are equal (no category found) if (changedContent.valueOf == content.valueOf) { $('#text-error-output').append('Category not found on '+pageToCat+'! '); return; }

//submit new page var config = { format: 'json', action: 'edit', watchlist: 'nochange', title: pageToCat, summary: 'Removing category ['+'['+cat+'|'+cat.substring(9)+']] (automatic)', nocreate: '', text: changedContent, bot: true, token: mw.user.tokens.get('editToken') };

if (mw.config.get("wgUserGroups").join(' ').indexOf('bot') == -1) delete config.bot;

$.ajax({                       url: mw.util.wikiScript('api'),                        data: config,                        dataType: 'json',                        type: 'POST',                        success: function(d) {                            if (!d.error) {                                console.log('Category successfully removed from '+pageToCat+'!');                            }                             else {                                console.log('Failed to remove category from '+pageToCat+': '+ d.error.code);                                $('#text-error-output').append('Failed to remove category from '+pageToCat+': '+ d.error.code +' ');                            }                        },                        error: function {                            console.log('Failed to remove category from '+pageToCat+'!'); $('#text-error-output').append('Failed to remove category from '+pageToCat+'! '); }                   });                }                else {                    console.log('Failed to get contents of page: '+ d.error.code);                    $('#text-error-output').append('Failed to get contents of '+pageToCat+': '+ d.error.code +' ');                }            }) .fail(function {               console.log('Failed to get contents of '+pageToCat+'!');                $('#text-error-output').append('Failed to get contents of '+pageToCat+'! ');           });        }        /* currently broken if (actionVal == 3) { //replace category var newCat = prompt('Please enter the replacement category name (no category prefix):'); if (!newCat) { alert('No name entered!'); document.getElementById('start-button').removeAttribute("disabled"); return; }

//get page contents new mw.Api.get({     action: 'query',      prop: 'revisions',      rvprop: 'content',      titles: pageToCat      }) .done(function(d) {	if (!d.error) {         for (var i in d.query.pages) {            if (d.query.pages[i].revisions) {	       var content = d.query.pages[i].revisions[0]["*"];            }            else {	      $('#text-error-output').append('Page '+pageToCat+' does not exist! ');	     return;            }          }

//replace old category var regex = new RegExp ("\\[\\[Category:"+cat+"\\]\\]","gi"); if ($('input[name=mass-categorization-removal]:checked').val == 2) regex = new RegExp ("\\[\\[Category:"+cat+"\\|?.*?\\]\\]","gi");

newCat = 'Category:'+ newCat.charAt(0).toUpperCase + newCat.substring(1); var changedContent = content.replace(regex,+newCat+); cat = 'Category:'+ cat.charAt(0).toUpperCase + cat.substring(1);

//don't submit if new and old contents are equal (no category found) if (changedContent.valueOf == content.valueOf) { $('#text-error-output').append('Category not found on '+pageToCat+'! '); return; }

//submit new page var config = { format: 'json', action: 'edit', watchlist: 'nochange', title: pageToCat, summary: 'Replacing category ['+'['+cat+'|'+cat.substring(9)+']] with ['+'['+newCat+'|'+newCat.substring(9)+']] (automatic)', nocreate: '', text: changedContent, bot: true, token: mw.user.tokens.get('editToken') };

if (mw.config.get("wgUserGroups").indexOf('bot') == -1) delete config.bot;

$.ajax({             url: mw.util.wikiScript('api'),              data: config,              dataType: 'json',              type: 'POST',              success: function(d) {                if (!d.error) {                  console.log('Category successfully replaced on '+pageToCat+'!');                } 	        else {	          console.log('Failed to remove category from '+pageToCat+': '+ d.error.code);	          $('#text-error-output').append('Failed to replace category on '+pageToCat+': '+ d.error.code +' ');                }              },              error: function {                console.log('Failed to remove category from '+pageToCat+'!');	        $('#text-error-output').append('Failed to replace category on '+pageToCat+'! ');             }          });	}	else { console.log('Failed to get contents of page: '+ d.error.code); $('#text-error-output').append('Failed to get contents of '+pageToCat+': '+ d.error.code +' '); }    })     .fail(function { console.log('Failed to get contents of '+pageToCat+'!'); $('#text-error-output').append('Failed to get contents of '+pageToCat+'! '); });   }   */        setTimeout(init,delay);    } }) (this.jQuery, this.mediaWiki);