MediaWiki:Common.js

// var hnp = { /*********	** Upload form scripts *********/	upload:{ /***		** PreloadForm ***/		PreloadForm:function { /// Fill the upload form with useful default values. if(wgNamespaceNumber != -1 || wgCanonicalSpecialPageName != 'Upload') { return; }			var textBox = $('#wpUploadDescription'); if(textBox.val === '') { textBox .val('==Citation==\n\n\n==Description==\n') ;			}		},		/***		** Preview ***/		Preview:function { /* extract data */ var uploadTitle = 'File:' + $('#wpDestFile').val; var uploadText = $('#wpUploadDescription').val; /* generate preview container */ var previewBox = $('#hnp-upload-preview'); if(!previewBox.length) { $('#mw-upload-form') .append(						$(document.createElement('fieldset'))							.append( $(document.createElement('legend')) .text('Preview') )							.append( previewBox = $(document.createElement('div')) .attr('id', 'hnp-upload-preview') )					)				;			}			else { previewBox.empty; }			/* show loading indicator */ previewBox .append(					$(document.createElement('img'))						.attr({ 'src':'http://upload.wikimedia.org/wikipedia/commons/3/32/Loader3.gif', 'alt':'' })					.append('Loading...')				) ;			/* fetch preview */ $.ajax({				/* request */				'type':'GET',				'url':location.protocol + '//' + location.hostname + wgScriptPath + '/api.php',				'data':{					'action':'parse',					'format':'json',					'text':uploadText,					'title':uploadTitle/*,					'prop':'text|categories'*/				},				/* handle response */				'success':function(data, textStatus, xhr) {					// text					previewBox.empty.html(data.parse.text['*']);					// categories					var cats = data.parse.categories;					if( cats.length ) {						/* build categories box */						var catBox;						previewBox							.append( $(document.createElement('div')) .attr({'id':'catlinks', 'class':'catlinks'}) .append(										catBox = $(document.createElement('div'))											.attr({'id':'mw-normal-catlinks'})											.append( $(document.createElement('a')) .attr({'href':wgArticlePath.replace('$1', 'Special:Categories'), 'title':'Special:Categories'}) .append('Categories') )											.append(': ')									) )						;						for( var i = 0, len = cats.length; i < len; i++ ) {							catBox								.append( $(document.createElement('a')) .attr({'href':wgArticlePath.replace('$1', 'Category:' + escape(cats[i]['*']))}) .text(cats[i]['*'].replace(/_/g, ' ')) )							;							if(i != len - 1) {								catBox.append(' | ');							}						}					}				},				/* handle error */				'error':function(xhr, textStatus, error) {					box						.empty						.append( $(document.createElement('div')) .addClass('error') .text('Oops, something went wrong! ' + xhr.status + ' (' + xhr.statusText + '): ' + textStatus + ' (' + error + ')') )					;				}			});		}	},	/*********	** Editing scripts *********/	editing:{ /***		** New page template suggestions ***/		DisplayNewPageTemplates:function { /* build templates */ var newPageTemplates = [ {					text:'Copyright permission by...', condition:wgNamespaceNumber == 14 && wgTitle.match(/^Copyright permission by/), handler:function { var name     = wgTitle.replace('Copyright permission by ', ''); var firstName = name.match(/^[^\s]+/); var lastName = name.replace(/^[^\s]+ ?/, ''); return ''; }				},				{					text:'Images by year', condition:wgNamespaceNumber == 14 && wgTitle.match(/^[\d\?]{4}s? files$/), handler:function { var date  = wgTitle.replace(/ files/, ''); var decade = date.match(/^../).toString; var year  = date.match(/..s?$/).toString; return ''; }				},				{					text:'Images by subject', condition:wgNamespaceNumber == 14, handler:function { var firstName = wgTitle.match(/^[^\s]+/); var date     = wgTitle.match(/\([^\)]+\)$/);						var lastName  = wgTitle.replace(/^[^\s]+\s*/, ).replace(/\s*\([^\)]+\)$/, ); return ''; }				},				{					text:'Images by family name', condition:wgNamespaceNumber == 14, handler:function { return ''; }				}			];			/* find container */ var container = $('#mw-newarticletext'); if(!container.length) { return; }			/* find available templates */ var templates = []; for(var t = 0, tLen = newPageTemplates.length; t < tLen; t++) { if(newPageTemplates[t].condition) { templates.push(newPageTemplates[t]); }			}			if(!templates.length) { return; }			/* build list structure */ var list; container .append(					$(document.createElement('div'))						.text('Do you want to use one of these templates?')						.css({'margin':'1em 0 0 0', 'padding':'0.5em', 'border':'1px solid #000'})						.append( list = $(document.createElement('ul')) .css({'list-style-type':'none'}) )				)			;			/* add menu items */ var _clickHandler = function(e) { var id = $(e.target).attr('data-template-id'); $('#wpTextbox1').val(templates[id].handler); $('#wpSummary').val('created'); e.preventDefault; };			for(var i = 0, len = templates.length; i < len; i++) { var obj = templates[i]; list.append(					$(document.createElement('li'))						.append( $(document.createElement('a')) .attr({'href':'#', 'data-template-id':i}) .text(obj.text) .click(_clickHandler) )				);			}		},		/***		** Add & sort file subjects ***/		AddAndSortSubjects:function(addSubjects) { var textBox = $('#wpUploadDescription, #wpTextbox1'); var text = textBox.val;

/* right-pad string with whitespace to specified width */ function padright(str, num) { var len = num - (''+str).length; for(var i=0; i<len; i++) { str += ' '; }				return str; }

/* extract subjects */ var subjects = []; var _temp = { reg_name: /\{\{(?:photograph of|document about)[^}]+\}\}[^\n\r\{\}]*/ig, width: 0, name_width: 0 };			_temp.matches = text.match(_temp.reg_name); _temp.text = text.replace(_temp.reg_name, ''); for( var i = 0, len = _temp.matches.length; i < len; i++ ) { /* extract details */ var template = _temp.matches[i].match(/\{\{([a-z\s]*)/i)[1].toString.trim; var name = _temp.matches[i].match(/\{\{[a-z\s]*\s*\|([^\|}]*)/i)[1].toString.trim; if( name === '' ) { continue; }				if( name.match(/^unknowns?$/i) ) { name = 'unknowns'; }

var notes = _temp.matches[i].match(/notes\s*=\s*([^\|\{\}]+)|^.+\}\}\s*\s*$/i); notes = (notes ? (notes[1] || notes[2]).toString.trim : '');

var added = _temp.matches[i].match(/added\s*=\s*[^\s\|\{\}]/i); added = ( added ? '1' : '' );

/* calculate width */ _temp.width = Math.max(_temp.width, template.length); _temp.name_width = Math.max(_temp.name_width, name.length);

/* store details */ subjects.push({					'name':name,					'notes':notes,					'added':added,					'template':template				}); }

/* sort subjects */ subjects.sort(function(a, b) {				/* unknowns */				if(a.name == 'unknowns') {					return -1;				}				else if(b.name == 'unknowns') {					return 1;				}

/* blanks */ else if(a.name === '') { return 1; }				else if(b.name === '') { return -1; }

/* alphabetical case */ else if(a.name < b.name) { return -1; }				else if(a.name > b.name) { return 1; }				return 0; });

/* rebuild list */ var output = ' |subjects = \n'; for( var s = 0, sLen = subjects.length; s < sLen; s++ ) { output += '  \n'; }			if( addSubjects ) { for( var p = 0; p < addSubjects; p++ ) { output += '  \n'; }				for( var d = 0; d < addSubjects; d++ ) { output += '  \n'; }			}

/* update text */ _temp.text = _temp.text.replace(/[\n\s]*\|[\n\s]*subjects[\n\s]*=[\n\s]*/i, '\n' + output); textBox.val(_temp.text); }	},

/*********	** UI scripts *********/	ui:{ /***		** Add metadata on subject category pages ***/		AddSubjectCategoryMetadata:function { /* exit if not on a subject category */ if(wgNamespaceNumber != 14 || !$('#category-subject')) { return; }

/* get list of unarticled images */ $.ajax({				/* request */				type:'GET',				url:location.protocol + '//' + location.hostname + wgScriptPath + '/api.php',				data:{'action':'query', 'list':'categorymembers', 'cmtitle':wgPageName, 'cmprop':'title|sortkey', 'cmlimit':'500', 'format':'xml'},				/* handle response */				success:function(data, textStatus, xhr) {					/* find unarticled files (their sort keys start with '0') */					$(data).find('cm[sortkey^=0]').each(function(i, item) { /* highlight their entry in the table */ item = $(item); var title = item.attr('title').replace(/^File:/, ''); $('#mw-category-media img[alt="' + title + '"]:first').closest('.gallerybox') .css({'border':'3px solid red'}) .append(								$(document.createElement('div'))									.css({'color':'red'})									.text('not in article')							) ;					});				},				/* handle error */				error:function(xhr, textStatus, error) {					$('#siteSub').after( $(document.createElement('div')) .attr('class', 'error') .text('Oops, something went wrong while fetching unarticled metadata: ' + xhr.status + ' (' + xhr.statusText + '): ' + textStatus + ' (' + error + ')') );				}			});			/* add event metadata */ if(location.hash.indexOf('sekret-metadata-test') != -1) { $('#mw-category-media .gallerytext > a').each(function(i, item) {					item = $(item);					$.ajax({ /* request */ type:'GET', url:location.protocol + '//' + location.hostname + wgScriptPath + '/index.php', data:{ 'title':item.attr('title'), 'action':'render' },						/* handle response */ success:function(data, textStatus, xhr) { /* extract metadata */ var events = $(data).filter('#metadata').text; if(!events) { return; }							events = events.split('|'); /* generate list */ var list; item.closest('.gallerybox').append(								list = $(document.createElement('ul'))									.css({'margin':0, 'list-style':'none', 'font-size':'0.8em'})							); /* add events */ for(var i = 0, len = events.length; i < len; i++) { list.append(									$(document.createElement('li'))										.text(events[i])								); }						},						/* handle error */ error:function(xhr, textStatus, error) { $('#siteSub').after(								$(document.createElement('div'))									.attr('class', 'error')									.text('Oops, something went wrong while fetching unarticled metadata: ' + xhr.status + ' (' + xhr.statusText + '): ' + textStatus + ' (' + error + ')')							); }					});				});			}		}	} };

$(document).ready(function {	hnp.upload.PreloadForm;	hnp.editing.DisplayNewPageTemplates;	hnp.ui.AddSubjectCategoryMetadata; });

/*############################################### function convertImageFormat { var textBox = document.getElementById('wpUploadDescription') || document.getElementById('wpTextbox1'); var text = textBox.value;
 * 1)  Temporary script to update deprecated image template format
 * 2)  by Jesse (Pathoschild)
 * 1)  by Jesse (Pathoschild)

/* refcode */ text = text.replace(/[\n\s]*refcode\s*=\s*\d*[\n\s]*/ig, '');

/* title prefix */ text = text.replace(/title prefix\s*=\s*/, 'page group = ');

/* convert subjects */ if(text.match('subject1')) { var subjects = []; /* parse format */ var regData = /subject(\d+)\s*=\s*(.+)/i; var names = text.match(/subject\d+[^\r\n]+[^\n\r\{\}]*/ig); for(var i = 0, len = names.length; i < len; i++) { /* number & name */ var number = names[i].match(regData)[1]; var name = names[i].match(regData)[2]; /* comment */ var comment = ''; if(name.match(//)) { comment = name.match(//)[1].toString; name = name.replace(//, ''); }			/* added? */			var added = text.match(new RegExp('added' + number + '\\s*=\\s*([a-z0-9]*)', 'i'))[1]; added = (added ? '1' : ' '); /* save details */ subjects.push({				'name':name,				'added':added,				'comment':comment			}); }		/* generate subject list */ var list = '\n |subjects = \n'; for(var s = 0, sLen = subjects.length; s < sLen; s++) { list += '  \n'; }		/* replace & remove old */ text = text.replace(/[\n\s]*\|\s*subject1\s*=[^\n]+[\n\s]*/i, list); text = text.replace(/[\n\s]*\|\s*(?:subject|added)\d+\s*\s*=[^\n]+/ig, ''); }	else { text = text.replace(/\{\{subject\s*\|/ig, '{{document about|'); }	textBox.value = text; sortUploadSubjects; } //