Jump to content

User:AlanM1/scripts/Citoid.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.
/*************

Generates a citation template from a url using the citoid server

Fix "}}" correctly -> "}}" instead of "}"  User:AlanM1 20141015d
Narrow url and code fields, use local Citoid.css to increase length 2em User:AlanM1 20141015c
Add option to put space before pipes User:AlanM1 20141015b
Escape '|' and "}}" in results User:AlanM1 20141015a
Add "query sent" message User:AlanM1 20141002d
Minor fixes to dates by User:AlanM1 20141001a
Copied from User:Salix alba/Citoid.js

Author User:Salix alba
Date: 31 Aug 2014
Version: 0.01

Heavily borrowed from 
User:Mvolz/veCiteFromURL.js

Interface element taken from
TemplateDataEditor
http://fr.wikipedia.org/w/index.php?title=Utilisateur:Ltrlg/scripts/TemplateDataEditor.js

 ***************/



function Citoid($) {

	////// Customization for local wikis
	lang = mw.config.get('wgUserLanguage');
	messages = {
			"en": {
				"toolbox-label": 'Citoid',
				"toolbox-tooltip": 'Generate reference from a URL',
				"title": 'Citoid reference ',
				"close": 'Close',
				"monthnames": ['January','February','March','April','May','June','July','August','September','October','November','December']
			},
	};
    if(messages[lang]==null) lang='en';

    var url;

    function formatCS1Date(isodate) {
    	var style = $( "input:radio[name=datestyle]:checked" ).val();
    	// Input format
    	// 012345678901234567890123
    	//"2014-09-28T20:03:10.298Z"
    	//alert('formatCS1Date("'+isodate+'")');	

		if (style == "YMD")
			return isodate.substr(0, 10);

		var monthIndex = parseInt(isodate.substr(5, 2), 10) - 1;
		var sday = parseInt(isodate.substr(8, 2), 10).toString();
    	if (style == "MDY")
    		return messages[lang].monthnames[monthIndex] + " " + sday + ", " + isodate.substr(0, 4);
    	else	// DMY
    		return sday + " " + messages[lang].monthnames[monthIndex] + " " + isodate.substr(0, 4);
	}
    
/* Returns a javascript object given search results */
	function getPlainObject( url, searchResults ) {
 
		var content, plainObject, d, templateHref, templateName,
			citation = JSON.parse( JSON.stringify( searchResults ) )[0], //uses the first citation result for the time being
 
		templateTypeMap = {
			book: 'Cite book',
			bookSection: 'Cite book',
			journalArticle: 'Cite journal',
			magazineArticle: 'Cite news',
			newspaperArticle: 'Cite news',
			thesis: 'Cite journal',
			letter: 'Citation',
			manuscript: 'Cite book',
			interview: 'Citation',
			film: 'Citation',
			artwork: 'Citation',
			webpage: 'Cite web',
			report: 'Cite journal',
			bill: 'Citation',
			hearing: 'Citation',
			patent: 'Citation',
			statute: 'Citation',
			email: 'Cite web',
			map: 'Citation',
			blogPost: 'Cite web',
			instantMessage: 'Citation',
			forumPost: 'Cite web',
			audioRecording: 'Citation',
			presentation: 'Cite journal',
			videoRecording: 'Citation',
			tvBroadcast: 'Citation',
			radioBroadcast: 'Citation',
			podcast: 'Citation',
			computerProgram: 'Citation',
			conferencePaper: 'Cite journal',
			'document': 'Citation',
			encyclopediaArticle: 'Cite journal',
			dictionaryEntry: 'Cite journal'
		},
 
			//Parameter map for Template:Citation on en-wiki
			//In the format citation-template-field:citoid-field
			citationParams = {
				'first1': 'author1-first',
				'last1': 'author1-last',
				'first2': 'author2-first',
				'last2': 'author2-last',
				'first3': 'author3-first',
				'last3': 'author3-last',
				'first4': 'author4-first',
				'last4': 'author4-last',
			//	'accessdate': 'accessDate',
				'title': 'title',
				'url': 'url',
				'publisher': 'publisher',
				//a large number of Zotero types have the field publicationTitle
				//however, in setting journal to publicationTitle, the citation
				//will be formatted as a journal article, which may not always be
				//desirable.
				'journal': 'publicationTitle',
			//	'newspaper': 'publicationTitle',
				'date': 'date',
				'location': 'place',
				'issn': 'ISSN',
				'isbn': 'ISBN',
				'pages': 'pages',
				'volume': 'volume',
				'series': 'series',
				'issue': 'issue',
				'doi': 'DOI'
			},
 
			webParams = {
				'first1': 'author1-first',
				'last1': 'author1-last',
				'first2': 'author2-first',
				'last2': 'author2-last',
				'first3': 'author3-first',
				'last3': 'author3-last',
				'first4': 'author4-first',
				'last4': 'author4-last',
			//	'accessdate': 'accessDate',
				'title': 'title',
				'url': 'url',
				'date': 'date',
				'publisher': 'publisher',
				'website': 'publicationTitle'
			},
 
			newsParams = {
				'first1': 'author1-first',
				'last1': 'author1-last',
				'first2': 'author2-first',
				'last2': 'author2-last',
				'first3': 'author3-first',
				'last3': 'author3-last',
				'first4': 'author4-first',
				'last4': 'author4-last',
			//	'accessdate': 'accessDate',
				'title': 'title',
				'url': 'url',
				'publisher': 'publisher',
				'newspaper': 'publicationTitle',
				'date': 'date',
				'location': 'place',
				'issn': 'ISSN',
				'isbn': 'ISBN',
				'pages': 'pages',
				'volume': 'volume',
				'series': 'series',
				'issue': 'issue',
				'doi': 'DOI'
			},
 
			bookParams = {
				'first1': 'author1-first',
				'last1': 'author1-last',
				'first2': 'author2-first',
				'last2': 'author2-last',
				'first3': 'author3-first',
				'last3': 'author3-last',
				'first4': 'author4-first',
				'last4': 'author4-last',
			//	'accessdate': 'accessDate',
				'title': 'title',
				'url': 'url',
				'publisher': 'publisher',
				'journal': 'publicationTitle',
				'date': 'date',
				'location': 'place',
				'issn': 'ISSN',
				'isbn': 'ISBN',
				'pages': 'pages',
				'volume': 'volume',
				'series': 'series',
				'issue': 'issue',
				'doi': 'DOI'
			},
 
			journalParams = {
				'first1': 'author1-first',
				'last1': 'author1-last',
				'first2': 'author2-first',
				'last2': 'author2-last',
				'first3': 'author3-first',
				'last3': 'author3-last',
				'first4': 'author4-first',
				'last4': 'author4-last',
			//	'accessdate': 'accessDate',
				'title': 'title',
				'url': 'url',
				'publisher': 'publisher',
				'journal': 'publicationTitle',
				'date': 'date',
				'location': 'place',
				'issn': 'ISSN',
				'isbn': 'ISBN',
				'pages': 'pages',
				'volume': 'volume',
				'series': 'series',
				'issue': 'issue',
				'doi': 'DOI'
			},
 
			//format 'template name':parameter obj name
			templateParamMap = {
				'Citation': citationParams,
				'Cite web': webParams,
				'Cite news': newsParams,
				'Cite journal': journalParams,
				'Cite book': bookParams
			},
 
			//This will contain the correct template with the fields filled out
			paramObj = {};
 
		templateName = templateTypeMap[citation.itemType];
 
		templateHref = 'Template:' + templateName;
 
		//hack for now- set citation url to supplied url if not given
		if (!citation.url) {citation.url =  url;}
 
		$.each( templateParamMap[templateName], function ( key, value ) {
			var objString = citation[value] !== undefined ? citation[value] : '';
			paramObj[key] = { 'wt': objString };
		} );
 
		d = new Date();
		//var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
		//ds = d.getDate() + " " + months[d.getMonth()] + " " + d.getGetFullYear();
		paramObj.accessdate = { 'wt': formatCS1Date(d.toISOString()) };
		//alert("paramObj.date.wt = '" + paramObj.date.wt + "'");
		var d2 = new Date(paramObj.date.wt);
		if (d2) {
			var s2 = (d2.getYear() + 1900).toString() + "-" + 
    					((d2.getMonth() + 101).toString()).substr(1, 2) + "-" + 
    					((d2.getDate() + 100).toString()).substr(1, 2);
			paramObj.date.wt = formatCS1Date(s2);
		}
 
 		// Greatly simplified return result
		plainObject = { //before paren put get plain object
			'templateName': templateName.toLowerCase(),
			'href': templateHref,
			'params': paramObj
		};
 
		return plainObject;
	};

    //// build the code for the template 
    
    function buildTemplateCode(obj) {
    	var res = "{{" + obj.templateName;
		var sep = $( "input:checkbox[name=spacepipe]:checked" ).val() ? " |" : "|";

    	$.each( obj.params, function ( key, value ) {
			// Replace pipes and double closing braces with HTML entities in wikicode 
			var wt = value.wt.replace(/\|/g, "|").replace(/}}/g, "}}");
			if(wt) {
				//console.log(key,wt);
				res = res + sep + key + "=" + wt;
			}
		} );
		res = res + "}}";
    	return res;
    }
    
	////// Called when toolbox button clicked

	function callCitoid() {
		url = $('#citoid-url').val();
        //alert("Call citoid url [" + url +"]");

 		var citoidService = "https://citoid.wmflabs.org/url";
		mw.notify("Sending query to Citoid server...");
		$.ajax( {
			beforeSend: function (request) {
				request.setRequestHeader('Content-Type', 'application/json');
			},
			url: citoidService,
			type: 'POST',
			data: JSON.stringify( { url: url } ),
			dataType: 'json',
			success: doneAjax,
			error: function ( XMLHttpRequest, textStatus, errorThrown) {
				mw.notify( 'Status:'  + textStatus +  'Error: ' + errorThrown );
			},
		} );
	}
				
	function doneAjax(result) {
        var plain = getPlainObject( url, result );	
        //console.log(result);
        //console.log(plain);
        var res = buildTemplateCode(plain);
        console.log(res);
        $('#citoid-code').text(res);
        //alert("doneAjax");
	}

	function openCitoidWindow() {
		$cont.fadeIn('slow');
	}

	///// Close the dialog
	function close() {
		$cont.fadeOut('slow', function(){
		});
	}

	////////// Building called after page loads 
	function buildHTML() {
		
		$button = $('<button>')
		.attr({ id: 'citoid-button', type:'button' })
		.text("Generate Citation")
		.click(callCitoid);
		
		$body = $('<div>')
		.attr('id', 'citoid-body')
		.append("<p>URL: "+
		    "<input type='text' id='citoid-url' size='150' /></p>")
		.append("<p>Date format: "+
		    "<input type='radio' name='datestyle' value='DMY' checked >1 September 2014</input>&nbsp;&nbsp;"+
		    "<input type='radio' name='datestyle' value='MDY'>September 1, 2014</input>&nbsp;&nbsp;"+
		    "<input type='radio' name='datestyle' value='YMD'>2014-09-01</input></p>")
		.append("<p>Space before pipe: "+
		    "<input type='checkbox' name='spacepipe' checked></input></p>")
		.append($button)
		.append("<p>Template code</p>")
		.append("<textarea id='citoid-code'>");
		
		$title = $('<h2>').text( messages[lang]['title'] );
		
		$cont = $('<div>')
		.attr('id', 'citoid-cont')
		.append($('<div>')
				.attr('id', 'citoid-dialog')
				.append( $title )
				.append($('<a>')
						.attr({
							id: 'citoid-close',
							href: '#',
							title: messages[lang]['close']
						})
						.click(function(){
							close();
							return false;
						})
						.append($('<img>')
								.attr({
									alt: messages[lang]['close'],
									src: '//upload.wikimedia.org/wikipedia/commons/thumb/8/8d/VisualEditor_-_Icon_-_Close.svg/24px-VisualEditor_-_Icon_-_Close.svg.png'
								})
						)
				)
				.append($body)
		)
		.hide();

		$(document.body).append($cont);
	}

	////// Adds a link in the toolbox
	function addPortletLink() {

		$(
			mw.util.addPortletLink('p-tb', '#', messages['en']['toolbox-label'], 'citoid', messages['en']['toolbox-tooltip'] )
		).click(function(){
			openCitoidWindow();
			return false;
		})
	}

	/////// Actions to do once page loads, 
	function start() {
		//alert("Citoid 0.01");
		addPortletLink();
		buildHTML();
	}

	////////// START //////////
	start(); 
}

/////// Wrapper code
//if( true
//  $.inArray( mw.config.get('wgNamespaceNumber'), [ 2, 10 ] ) !== -1 
// && $.inArray( mw.config.get('wgAction'), [ 'edit', 'submit' ] ) !== -1  */ ) {

mw.loader.load( 
  	  '//en.wikipedia.org/w/index.php?title=User:AlanM1/Citoid.css&action=raw&ctype=text/css&smaxage=21600&maxage=86400',
	'text/css' );
mw.loader.using('mediawiki.util', function(){
	  $(document).ready(Citoid);
        });