Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page.
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.
mw.loader.using(['mediawiki.util'],function(){$(document).ready(function(){if((mw.config.get('wgNamespaceNumber')!==0&&mw.config.get('wgPageName')!=='User:Polygnotus/dupreftest')||mw.config.get('wgAction')!=='view'){return;}letreferencesHeading=document.getElementById("References");if(!referencesHeading){return;}conststyle=document.createElement('style');style.textContent=` li:target { border: 4px dotted red; padding: 2px; background-color: #ffcccc !important;} .duplicate-citation-highlight { background-color: #ffe6e6; } .duplicate-citation-hover { background-color: #ffcccc; } .duplicate-citation-clicked { background-color: #ffeeee; } `;document.head.appendChild(style);letparentDiv=referencesHeading.closest("div");letnewParagraph=document.createElement("p");newParagraph.style.color="red";functionaddDuplicateCitationsTemplate(){varapi=newmw.Api();varpageTitle=mw.config.get('wgPageName');// First, get the duplicate informationletduplicateInfo=getDuplicateInfo();api.get({action:'query',prop:'revisions',titles:pageTitle,rvprop:'content',rvslots:'main',formatversion:2}).then(function(data){varpage=data.query.pages[0];varcontent=page.revisions[0].slots.main.content;// Add the template at the top of the pagevarnewContent='{{Duplicate citations}}\n'+content;// Create the edit summaryletsummary='+{{Duplicate citations}}';if(duplicateInfo.length>0){summary+=': ';duplicateInfo.forEach((info,index)=>{summary+=`${info.url} (refs: ${info.refs.join(', ')})`;if(index<duplicateInfo.length-1){summary+='; ';}});}// Make the editreturnapi.postWithToken('csrf',{action:'edit',title:pageTitle,text:newContent,summary:summary});}).then(function(){mw.notify('Successfully added the Duplicate citations template!');// Reload the page to show the changes___location.reload();}).catch(function(error){console.error('Error:',error);mw.notify('Failed to add the template. See console for details.',{type:'error'});});}functiongetDuplicateInfo(){constreferenceSpans=document.querySelectorAll('span.reference-text');consturlMap=newMap();constduplicates=[];referenceSpans.forEach((span)=>{constlinks=span.querySelectorAll('a');constrefNumber=span.closest('li')?.id.split('-').pop()||'Unknown';letvalidLink=null;for(letlinkoflinks){consturl=link.href;constlinkText=link.textContent.trim();if(linkText!=="Archived"&&!url.includes("wikipedia.org/wiki/")&&!url.includes("_(identifier)")){validLink=link;break;}}if(validLink){consturl=validLink.href;if(urlMap.has(url)){urlMap.get(url).push(refNumber);}else{urlMap.set(url,[refNumber]);}}});urlMap.forEach((refs,url)=>{if(refs.length>1){duplicates.push({url,refs});}});returnduplicates;}functioncalculateSimilarity(str1,str2){constlonger=str1.length>str2.length?str1:str2;constshorter=str1.length>str2.length?str2:str1;constlongerLength=longer.length;if(longerLength===0){return1.0;}return(longerLength-editDistance(longer,shorter))/parseFloat(longerLength);}functioneditDistance(s1,s2){s1=s1.toLowerCase();s2=s2.toLowerCase();constcosts=newArray();for(leti=0;i<=s1.length;i++){letlastValue=i;for(letj=0;j<=s2.length;j++){if(i==0)costs[j]=j;else{if(j>0){letnewValue=costs[j-1];if(s1.charAt(i-1)!=s2.charAt(j-1))newValue=Math.min(Math.min(newValue,lastValue),costs[j])+1;costs[j-1]=lastValue;lastValue=newValue;}}}if(i>0)costs[s2.length]=lastValue;}returncosts[s2.length];}functiongetAllVisibleText(element){if(element.nodeType===Node.TEXT_NODE){returnelement.textContent.trim();}if(element.nodeType===Node.ELEMENT_NODE){if(window.getComputedStyle(element).display==='none'){return'';}returnArray.from(element.childNodes).map(child=>getAllVisibleText(child)).join(' ').replace(/\s+/g,' ').trim();}return'';}functionextractVisibleText(htmlString){constparser=newDOMParser();constdoc=parser.parseFromString(htmlString,'text/html');returngetAllVisibleText(doc.body);}functioncheckDuplicateReferenceLinks(){constreferenceSpans=document.querySelectorAll('span.reference-text');consturlMap=newMap();constduplicates=newMap();lettotalLinks=0;// Create a map of cite_note ids to their correct reference numbersconstciteNoteMap=newMap();document.querySelectorAll('.reference').forEach(ref=>{constlink=ref.querySelector('a');if(link){constlinkHref=link.getAttribute('href');if(linkHref){constciteNoteId=linkHref.substring(1);// Remove the leading '#'constrefNumber=citeNoteId.split('-').pop();citeNoteMap.set(citeNoteId,refNumber);}}});referenceSpans.forEach((span)=>{constlinks=span.querySelectorAll('a');constciteNote=span.closest('li')?.id;constrefNumber=citeNoteMap.get(citeNote)||'Unknown';constrefText=extractVisibleText(span.outerHTML);// Extract visible text contentletvalidLink=null;for(letlinkoflinks){consturl=link.href;constlinkText=link.textContent.trim();if(linkText!=="Archived"&&!url.includes("wikipedia.org/wiki/")&&!url.includes("_(identifier)")){validLink=link;break;}}if(validLink){consturl=validLink.href;totalLinks++;if(urlMap.has(url)){if(duplicates.has(url)){duplicates.get(url).push({refNumber,citeNote,refText});}else{duplicates.set(url,[urlMap.get(url),{refNumber,citeNote,refText}]);}}else{urlMap.set(url,{refNumber,citeNote,refText});}}});if(duplicates.size>0){if(document.querySelector('table.box-Duplicated_citations')===null){consteditSections=parentDiv.querySelectorAll('span.mw-editsection');editSections.forEach(editSection=>{letspanBefore=document.createElement('span');spanBefore.className='mw-editsection-bracket';spanBefore.textContent='[';letaddTemplateLink=document.createElement('a');addTemplateLink.textContent=' add {{duplicated citations}} ';addTemplateLink.href='#';addTemplateLink.addEventListener('click',function(e){e.preventDefault();addDuplicateCitationsTemplate();});letspanAfter=document.createElement('span');spanAfter.className='mw-editsection-bracket';spanAfter.textContent=']';editSection.appendChild(spanBefore);editSection.appendChild(addTemplateLink);editSection.appendChild(spanAfter);});}duplicates.forEach((refInfo,url)=>{letparagraphInfo=document.createElement('span');leturlLink=document.createElement('a');urlLink.href=url;urlLink.textContent=url;urlLink.target="_blank";urlLink.rel="noopener noreferrer";paragraphInfo.appendChild(document.createTextNode('Duplicate URL: '));paragraphInfo.appendChild(urlLink);paragraphInfo.appendChild(document.createTextNode(' in refs: '));refInfo.forEach((ref,index)=>{if(ref.citeNote){letlink=document.createElement('a');link.href=`#${ref.citeNote}`;link.textContent=ref.refNumber;paragraphInfo.appendChild(link);// Highlight only the specific duplicates on hoverlink.addEventListener('mouseover',()=>{refInfo.forEach(duplicate=>{constcitationElement=document.getElementById(duplicate.citeNote);if(citationElement){if(duplicate.citeNote===ref.citeNote){citationElement.classList.add('duplicate-citation-hover');}else{citationElement.classList.add('duplicate-citation-highlight');}}});});link.addEventListener('mouseout',()=>{refInfo.forEach(duplicate=>{constcitationElement=document.getElementById(duplicate.citeNote);if(citationElement){citationElement.classList.remove('duplicate-citation-hover');citationElement.classList.remove('duplicate-citation-highlight');}});});// Highlight duplicates on click and allow navigationlink.addEventListener('click',()=>{// Remove previous click highlightsdocument.querySelectorAll('.duplicate-citation-clicked').forEach(el=>{el.classList.remove('duplicate-citation-clicked');});// Add new click highlightsrefInfo.forEach(duplicate=>{constcitationElement=document.getElementById(duplicate.citeNote);if(citationElement){citationElement.classList.add('duplicate-citation-clicked');}});// The default behavior (navigation) will now occur});}else{paragraphInfo.appendChild(document.createTextNode(ref.refNumber));}// Calculate similarity with the next referenceif(index<refInfo.length-1){constsimilarity=calculateSimilarity(ref.refText,refInfo[index+1].refText);constsimilarityPercentage=Math.round(similarity*100);paragraphInfo.appendChild(document.createTextNode(` (${similarityPercentage}%)`));}if(index<refInfo.length-1){paragraphInfo.appendChild(document.createTextNode(', '));}});paragraphInfo.appendChild(document.createElement('br'));newParagraph.appendChild(paragraphInfo);});parentDiv.after(newParagraph);}}checkDuplicateReferenceLinks();});});