User:Kangaroopower/autoArchive.js

// // Oh btw I'm not Daniel Friesen, thats User:Dantman. I just copied this script from wikia and adapted it for WP /* * Copyright © 2009, Daniel Friesen * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: *    * Redistributions of source code must retain the above copyright *      notice, this list of conditions and the following disclaimer. *    * Redistributions in binary form must reproduce the above copyright *      notice, this list of conditions and the following disclaimer in the *      documentation and/or other materials provided with the distribution. *    * Neither the name of the script nor the *      names of its contributors may be used to endorse or promote products *      derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY DANIEL FRIESEN AS IS AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL DANIEL FRIESEN BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ $(function {	var userconfig = (window.ArchiveToolConfig) ? window.ArchiveToolConfig : {};	var config = $.extend(true, { archiveListTemplate: window.archiveListTemplate || 'archives', archivePageTemplate: window.archivePageTemplate || 'talkarchive', archiveSubpage: 'Archive' }, userconfig);	window.autoArchive = {		version: '1.17',		/* Initialize the script */		init: function {			if (mw.config.get('wgNamespaceNumber') !== 501 && mw.config.get('wgNamespaceNumber') > 0 && mw.config.get('wgAction') === "view") {				mw.util.addPortletLink('p-cactions', 'javascript:window.autoArchive.start;', "Archive", "ca-Archive", "Archive");			}		},		start: function  {			var c = 'archives'.substr(0,1),				archiveListRegex = '['+c.toUpperCase+c.toLowerCase+']'+'archives'.substr(1),				bc = $("#bodyContent").addClass('archiving').empty,				rev, content;				$('').appendTo(bc);				$.getJSON(mw.util.wikiScript( 'api') + "?action=query&prop=revisions&titles=" + mw.config.get('wgPageName') + "&rvprop=timestamp|content&format=json", function(q) { bc.empty; var rev = q.query.pages[wgArticleId].revisions[0]; content = rev['*']; });				var lines = window.content.split('\n'); 				var table = $(' ').appendTo(bc);				var ul = $(' ').appendTo(table);				for ( var l = 0; l < lines.length; l++ ) {					var line = lines[l];					$(' ').toggleClass('noarchive', (new RegExp('^\\{\\{'+archiveListRegex+'\}\}')).test(line))						.attr({line:line})						.append( $(' ').text(line).append(' ') ).appendTo(ul);				}				var sections = [];				var sectionEnd = lines.length-1;				for ( var l = lines.length-1; l >= 0; l-- ) {					var line = lines[l];					if ( /^=.+?=/.test(line) || l === 0 ) {						var section = { start: l, end: sectionEnd };						section.length = section.end - section.start + 1;						sections.unshift(section);						sectionEnd = l-1;					}				}				var section;				while( section = sections.shift ) {					var tr = ul.children.eq(section.start);					$(' ').attr({rowspan: section.length}).appendTo(tr);				}				$(' ').append( $("").click(function(e) {						e.preventDefault;						ul.children('tr').addClass('archive');					}), ' ', $("").click(function(e) {					e.preventDefault;					ul.children('tr').removeClass('archive');				}), ' ', $("").click(function(e) {					window.autoArchive.archive(bc);				}), ' ', $('').click(function(e) {					bc.find('.ajax').remove;					location = mw.util.wikiScript( 'index')+'?title='+ mw.config.get('wgPageName')+'&action=purge';				}) ).prependTo(bc).clone(true).appendTo(bc);				var click = false;				var add;				table.mousedown(function(e) { e.preventDefault; var $li = $(e.target).closest('tr'); if(!$li.length) return; var $section = $(e.target).closest('.section'); if ( $section.length ) { var slist = $li.nextAll(':lt('+(parseInt($section.attr('rowspan'),10)-1)+')').addBack; var sadd = slist.filter(function { return !$(this).hasClass('archive') }).length; slist.toggleClass('archive', !!sadd); return; }					click = true; add = !$li.hasClass('archive'); $li.toggleClass('archive', !!add); });				table.mouseover(function(e) { if (!click) return; var $li = $(e.target).closest('tr'); if(!$li.length) return; $li.toggleClass('archive', !!add); });				$('body').mouseup(function(e) { click = false; });		},		archive : function(bc) {			var talkLines = [];			var archiveLines = [];			var ul = $(' ').appendTo(table);			ul.children.each(function { var arr = $(this).hasClass('noarchive') || !$(this).hasClass('archive') ? talkLines : archiveLines; arr.push( $(this).attr('line') ); });			if ( !(new RegExp('^\\{\\{'+archiveListRegex+'\}\}')).test(talkLines[0]) )				talkLines = [, ].concat(talkLines);				archiveLines = [, ].concat(archiveLines);				bc.empty;				$('').attr({src:'http://images.wikia.nocookie.net/__cb51261/common/skins/common/progress-wheel.gif'}).appendTo(bc);				window.autoArchive.findArchive(talkLines.join('\n'), archiveLines.join('\n'), bc);		},		findArchive: function(talkContent, archiveContent, bc) {			var archiveTitle,				qt,				archiveNo = 1,				m = $(' Finding archive id: ').appendTo(bc);			$.getJSON(mw.util.wikiScript( 'api') + "?action=query&list=allpages&apnamespace="+ mw.config.get('wgNamespaceNumber') + "&apprefix=" + mw.config.get('wgTitle') +'/'+ config.archiveSubpage +"&aplimit=max&apdir=ascending&format=json", function(q) { $.each(q.query.allpages, function(index, value) {					qt = parseInt(q.query.allpages[index].title.substr(mw.config.get('wgPageName').length+("/"+config.archiveSubpage).length), 10);						if (qt >= archiveNo) {							archiveNo = qt+1;						}				}); archiveTitle = mw.config.get('wgPageName') +'/'+config.archiveSubpage+' '+archiveNo; m.append('done... (using '+archiveNo+')'); window.autoArchive.saveArchive(archiveTitle, talkContent, archiveContent); });		},		saveArchive: function(archiveTitle, talkContent, archiveContent, bc) {			var m = $(' Saving archive page: ').appendTo(bc);			$.postJSON(mw.util.wikiScript( 'api') + "?action=edit&title="+ archiveTitle +"&text="+ archiveContent +"&summary=ArchiveTool: Archiving from " + mw.config.get('wgPageName') + ".&minor=true&createonly=true&format=json&token="+mw.user.tokens.get('csrfToken'), function(q) { if ( q.error && q.error.code === "articleexists" ) { m.append('failed...'); bc.append(" The archive page we tried to create already exists. "); return window.autoArchive.abort(bc); } else { m.append('done...'); window.autoArchive.saveTalk(archiveTitle, archiveNo, talkContent, bc); }			});		},		saveTalk: function(talkContent, bc){			var m = $(' Updating talk page: ').appendTo(bc);			$.postJSON(mw.util.wikiScript( 'api') + "?action=edit&title="+ mw.config.get('wgPageName') +"&text="+ talkContent +"&token="+ mw.user.tokens.get('csrfToken') +"&summary=Archiving to talk page (ArchiveTool)&minor=true&format=json", function(q) { if ( q.edit.result === "Success" ) { m.append('done...'); bc.find('.ajax').remove; window.document.location = mw.util.wikiScript('index') +'?title='+ mw.config.get('wgPageName') +'&action=purge'; } else { m.append('failed...'); bc.append(" Failed to update talkpage, you may wish to have the archive subpage we just created deleted. "); return window.autoArchive.abort(bc); }			});		},		abort: function(bc) {			bc.find('.ajax').remove;			bc.append(" Aborting... ");			$(" You may want to ").append( $('refresh').attr({href: mw.config.get('wgServer')+mw.config.get('wgArticlePath').replace('$1', mw.config.get('wgPageName'))}) ).append(' and try again.').appendTo(bc);		}	};	$(document).ready( window.autoArchive.init ); }); //