User:KokoroSenshi/MediaWiki:Gadget-Sandbox1.js

/* Preview button for file uploads. Adapted from http://commons.wikimedia.org/wiki/MediaWiki:UploadForm.js by Lupo, March 2008. Adaptation by http://rationalwiki.org/wiki/User:Nx Source: http://rationalwiki.org/wiki/MediaWiki:UploadPreview.js Modified for compatibility with Zelda Wiki's FileInfo template. License: GPL

var pageName = mw.config.get('wgPageName');

var canonicalNamespace = mw.config.get("wgCanonicalNamespace"); var canonicalSpecialPageName = mw.config.get("wgCanonicalSpecialPageName"); var script = mw.config.get("wgScript"); var scriptPath = mw.config.get("wgScriptPath"); var articlePath = mw.config.get("wgArticlePath"); var server = mw.config.get("wgServer");

var wpPreviewUploadLbl = "Show preview"; var wpPreviewUploadTooltip = "Preview your changes, please use this before saving!"; var wpPreviewOverwriteError ='You will upload over an already existing file.' +'If you proceed, the information in this form will not appear on the description page.';

var wpCategoriesUploadLbl = "Categories:";

if (typeof(UploadForm) == 'undefined') { //(If UploadForm already exist don't overwrite it)

var UploadForm = {

isInstalled : false, isReupload : false, the_form : null, install : function { //Check stuff first if (UploadForm.isInstalled) return; // Stop if already installed UploadForm.isInstalled = true; if (pageName !== 'Special:Upload') return; //Stop if not Special:Upload if (document.URL.indexOf('uploadpreview=disabled') > -1) return; // Stop if inidcate disabled var form = document.getElementById('mw-upload-form'), summary = document.getElementById('wpUploadDescription'); if (!form || !summary) return; // Stop if no form nor summary elements var reupload = document.getElementById('wpForReUpload'), //A hidden element for a reupload (that has value 1?) destFile = document.getElementById('wpDestFile'); //Destination filename inputbox if (reupload || document.URL.indexOf('wpForReUpload=1') > -1) { UploadForm.isReupload = true; }		UploadForm.the_form = form; if (!UploadForm.isReupload) { UploadForm.check_initial_dest_file; //doublecheck the filename first UploadForm.addPreviewButton; }	},	check_initial_dest_file : function { //Make the page check the filename again var destFile = document.getElementById('wpDestFile'); if (  destFile && destFile.value && destFile.value.length > 0                 //Make sure the dest file exists		    && wgUploadWarningObj && typeof(wgUploadWarningObj.keypress) == 'function' //Make sure the obj exists and is a function		    ) { wgUploadWarningObj.keypress; }	},	makePreview : function(summaryText, isOverwrite) { if (isOverwrite) { UploadForm.showPreview (				'\' +				'\' +				wpPreviewOverwriteError +				'\<\/div\>' +				'\<\/div\>'			); } else { var previewWarning = '\\n' + '\\n' + '\{\{int:previewnote\}\}\n' + '\<\/div>\n', sourceText   = $("#mw-input-source").val, licensingText = $("#mw-input-licensing").val, typeText     =  $("#mw-input-type").val, gameText     = $("#mw-input-game").val, text = " Preview \n" + "";			// Make the Ajax call // SO... what's this do? var req = sajax_init_object ; if (!req) return; var button = document.getElementById ('wpUploadPreview'); var page  = document.getElementById ('wpDestFile'); if (page) page = page.value; if (page != null && page.length == 0) page = null; if (button && typeof (injectSpinner) == 'function') injectSpinner (button, 'wpUploadPreviewSpinner'); var uri = server + scriptPath + '/api.php'; var args = 'action=parse&pst&text=' + encodeURIComponent (text) + (page ? '&title=File:' + encodeURIComponent (page.replace (/ /g, '_')) : "") + '&prop=text|categories&format=json'; // "&pst" is "Pre-save transform": tilde replacement, pipe magic for links like foo. // Don't use a callback directly, add the function call ourselves *after* the call, since // the API somehow resolves tildes to an IP number instead of the username if a callback // is used. C.f. https://bugzilla.wikimedia.org/show_bug.cgi?id=16616 // Apparently, that's a feature, not a bug... var request_length = uri.length + args.length + 1; if (!!window.ActiveXObject && request_length > 2000 || request_length > 8100) { // IE has a URL limit of 2083 character (2048 in the path), WMF servers appear to have an 8kB // limit; req.open ('POST', uri, true); req.setRequestHeader ('Content-Type', 'application/x-www-form-urlencoded'); } else { uri += '?' + args; args = null; req.open ('GET', uri, true); }			req.setRequestHeader ('Pragma', 'cache=no'); req.setRequestHeader ('Cache-Control', 'no-transform'); req.onreadystatechange = function {			 if (req.readyState != 4) return; if (typeof (removeSpinner) == 'function') removeSpinner ('wpUploadPreviewSpinner'); if (req.status != 200) return; // Add the "callback"... if (req.responseText && req.responseText.indexOf ('{') == 0) // Primitive sanity check. If the response text does *not* start with '{', it might have been // spoofed and contain a function call... of course, this simple check cannot catch more // elaborate spoof attempts. eval ('UploadForm.jsonPreview (' + req.responseText + ')'); };			req.send (args); }	},

jsonPreview : function (result) {   if (result && result.parse && result.parse.text && result.parse.text['*'] != null) { var txt = result.parse.text['*']; var categories = result.parse.categories; if (categories && categories.length > 0) { // Add a mock-up of a category bar. We don't care about non-existing categories, and we       // can't identify hidden categories. var catbar = ' ' + wpCategoriesUploadLbl; categories.sort (         function (a, b) {            var key_a = a['*'].toLowerCase, key_b = b['*'].toLowerCase ;            if (key_a < key_b) return -1;            if (key_a > key_b) return 1;            return 0;          }        ); for (var i = 0; i < categories.length; i++) { var catname = categories[i]['*']; if (catname && catname.length > 0) { if (i > 0) catbar += ' |'; catbar += ' ' + catname.replace(/_/g, ' ') + ''; }       }        catbar += '  '; // Now insert it into text. var end = txt.lastIndexOf (' '); txt += catbar; }     UploadForm.showPreview (txt); } },

isOverwrite : function { if (document.getElementById ('wpUploadWarningFileexists') != null) return true; var destfile_warning = document.getElementById ('wpDestFile-warning'); if (destfile_warning == null) return false; var dest_file = document.getElementById ('wpDestFile'); if (dest_file == null || dest_file.value == null || dest_file.value.length == 0) return false; var lks = destfile_warning.getElementsByTagName ('a'); if (lks == null || lks.length == 0) return false; var fn1 = dest_file.value.replace(/^\s\s*/, ).replace(/\s\s*$/, ).replace(/ /g, '_'); fn1    = fn1.substr (0, 1).toUpperCase  + fn1.substring (1); var fn0 = 'Image:' + fn1; fn1    = 'File:' + fn1; // Trimmed, blanks replaced by underscores, first character capitalized

for (var i = 0; i < lks.length; i++) { var href = lks[i].getAttribute ('href', 2); if (href.indexOf (script + '?') == 0 || href.indexOf (server + script + '?') == 0) { var m = /[&?]title=([^&]*)/.exec (href); if (m && m.length > 1) href = m[1]; else href = null; } else { var prefix = articlePath.replace ('$1', ""); if (href.indexOf (prefix) != 0) prefix = server + prefix; // Fully expanded URL? if (href.indexOf (prefix) == 0) href = href.substring (prefix.length); else href = null; }     if (!href) continue; href = decodeURIComponent (href).replace (/ /g, '_'); if (href == fn0 || href == fn1) return true; }   return false; },

isChildOf : function (child, ancestor) {   if (!ancestor) return false; while (child && child != ancestor) child = child.parentNode; return (child == ancestor); },

showPreview : function (result) {   var preview = document.getElementById ('wpUploadPreviewDisplay'); if (preview == null) { var before = document.getElementById ('mw-upload-permitted'); if (!before || UploadForm.isChildOf (before, UploadForm.the_form)) before = UploadForm.the_form; if (!before) return; // Don't know where to insert preview display. Error message here? preview = document.createElement ('div'); preview.setAttribute ('id', 'wpUploadPreviewDisplay'); before.parentNode.insertBefore (preview, before); }   try { preview.innerHTML = result; } catch (ex) { preview.innerHTML = ""; // Error message here instead? }   preview.style.display = ""; // Show it    preview.scrollIntoView; },

addPreviewButton : function {   var request = sajax_init_object ; // If we don't have Ajax, our preview won't work anyway. if (request == null) return; var uploadButton = document.getElementsByName ('wpUpload')[0]; // Has no ID...   // If we can't find the upload button, we don't know where to insert the preview button. if (uploadButton == null) return;

var previewButton = document.createElement ('input'); previewButton.setAttribute ('id', 'wpUploadPreview'); previewButton.setAttribute ('name', 'wpUploadPreview'); previewButton.type   = 'button'; previewButton.accessKey = 'p'; previewButton.value  = wpPreviewUploadLbl; previewButton.title  = wpPreviewUploadTooltip + ' [p]'; previewButton.onclick = UploadForm.preview;

previewButton.setAttribute ('style', 'margin-left: 0.5em;'); updateTooltipAccessKeys([previewButton]); uploadButton.parentNode.insertBefore (previewButton, uploadButton.nextSibling); },

preview : function (evt) {   var overwrite = UploadForm.isOverwrite ; var desc = document.getElementById ('wpUploadDescription'); UploadForm.makePreview (desc.value, overwrite); return true; }

};

} $(document).ready(UploadForm.install);