Jump to content
Wikipedia The Free Encyclopedia

User:CFA/scripts/attributetranslation.js

From Wikipedia, the free encyclopedia
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.
This user script seems to have a documentation page at User:CFA/scripts/attributetranslation.
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.
 //<nowiki>
 (function(){
 'use strict';

 constts=Date.now()+(29*24*60*60*1000);
 constpageName=mw.config.get('wgPageName');
 constpageTitle=pageName.replace(/_/g,' ');

 functiongetTalkPageTitleFrom(titleOrName){
 constt=mw.Title.newFromText(titleOrName);
 if(!t)return'Talk:'+pageTitle;
 consttalk=t.getTalkPage();
 returntalk?talk.getPrefixedText():'Talk:'+pageTitle;
 }

 functioncreateInputGUI(contributors){
 vargui=document.createElement('div');
 gui.style.position='fixed';
 gui.style.top='50%';
 gui.style.left='50%';
 gui.style.transform='translate(-50%, -50%)';
 gui.style.backgroundColor='#f8f9fa';
 gui.style.border='1px solid #a2a9b1';
 gui.style.padding='20px';
 gui.style.zIndex=10000;
 gui.style.overflowY='auto';
 gui.style.maxHeight='80vh';
 gui.innerHTML=`
  <label for="langCode" style="font-weight:bold">Language code</label>
  <p style="font-size: 50%;">The two-letter language code of the Wikipedia that this article was translated from.</p>
  <input type="text" id="langCode" placeholder="e.g. zh, es, fr"><br><br>
  <label for="articleName" style="font-weight:bold">Article name</label>
  <p style="font-size: 50%;">The name of the page on the other Wikipedia that this article was translated from.</p>
  <input type="text" id="articleName" placeholder="e.g. 维基百科"><br><br>
  <label for="addTranslatedPageTemplate" style="font-weight:bold">
  <input checked type="checkbox" id="addTranslatedPageTemplate"> Add {{Translated page}} to talk page
  </label>
  <p style="font-size: 50%;margin-bottom:1rem;">Add <a href="/wiki/Template:Translated page">{{Translated page}}</a> to the talk page <a href="/wiki/Help:Translation#License requirements">if</a> the translated content is significant.</p>
  <label style="font-weight:bold">Warn users</label>
  <div id="contributorsContainer">
  <div id="contributorsList"></div>
  </div><br>
  <button id="submitTranslation">Submit</button>
  <button id="closeGUI">Close</button>
  <div id="logContainer" style="display: none; margin-top: 20px; border-top: 1px solid #a2a9b1; padding-top: 10px;">
  <h3>Log</h3>
  <ul id="logList" style="list-style-type: none; padding-left: 0;"></ul>
  </div>
  `;

 document.body.appendChild(gui);

 varcontributorsList=document.getElementById('contributorsList');
 if(!contributorsList){
 console.error('Contributors list container not found.');
 return;
 }

 contributors.forEach(function(contributor){
 varcheckbox=document.createElement('input');
 checkbox.type='checkbox';
 checkbox.style="transform: scale(0.75);margin-right:3px;";
 checkbox.name='contributors';
 checkbox.value=contributor.username;
 varlabel=document.createElement('label');
 label.style="font-size:75%";
 label.appendChild(checkbox);
 label.appendChild(document.createTextNode(`${contributor.username}${contributor.edits} edit${contributor.edits===1?'':'s'}${contributor.isCreator?' (Page Creator)':''}`));
 label.appendChild(document.createElement('br'));
 contributorsList.appendChild(label);
 });

 document.getElementById('submitTranslation').addEventListener('click',function(){
 varlangCode=document.getElementById('langCode').value.trim();
 vararticleName=document.getElementById('articleName').value.trim();
 varselectedContributors=Array.from(document.querySelectorAll('input[name=contributors]:checked')).map(function(checkbox){
 returncheckbox.value;
 });
 varaddTemplate=document.getElementById('addTranslatedPageTemplate').checked;

 if(langCode&&articleName){
 processTranslation(langCode,articleName,selectedContributors,addTemplate);
 document.getElementById('logContainer').style.display='block';
 }else{
 alert('Please fill in both fields.');
 }
 });

 document.getElementById('closeGUI').addEventListener('click',function(){
 document.body.removeChild(gui);
 });
 }

 functionprocessTranslation(langCode,articleName,selectedContributors,addTemplate){
 vareditSummary=`This article contains content translated from the Wikipedia article at [[${langCode}:${articleName}]]; see its history for attribution. ([[User:CFA/scripts/AttributeTranslation|AT]])`;

 vartasksCompleted=0;
 vartotalTasks=1+(addTemplate?1:0)+selectedContributors.length;
 varlogList=document.getElementById('logList');

 functionaddLogEntry(message,success){
 varlistItem=document.createElement('li');
 listItem.style.display='flex';
 listItem.style.alignItems='center';

 varcheckmark=document.createElement('span');
 checkmark.style.display='inline-block';
 checkmark.style.width='16px';
 checkmark.style.height='16px';
 checkmark.style.marginRight='8px';
 checkmark.style.backgroundColor=success?'green':'red';
 checkmark.style.borderRadius='50%';

 listItem.appendChild(checkmark);
 listItem.appendChild(document.createTextNode(message));
 logList.appendChild(listItem);
 }

 functioncheckCompletion(){
 tasksCompleted++;
 if(tasksCompleted===totalTasks){
 setTimeout(()=>location.reload(),1000);
 }
 }

 $.ajax({
 url:mw.util.wikiScript('api'),
 type:'GET',
 data:{
 format:'json',
 action:'query',
 prop:'revisions',
 rvprop:'content',
 rvslots:'main',
 titles:pageTitle
 },
 success:function(data){
 varpages=data.query.pages;
 varpageContent='';
 for(varpageIdinpages){
 if(!pages.hasOwnProperty(pageId))continue;
 varrev=pages[pageId].revisions&&pages[pageId].revisions[0];
 pageContent=(rev&&rev.slots&&(rev.slots.main['*']||rev.slots.main['content']))||'';
 }
 pageContent+='\n\u200B';

 $.ajax({
 url:mw.util.wikiScript('api'),
 type:'POST',
 data:{
 format:'json',
 action:'edit',
 title:pageTitle,
 text:pageContent,
 summary:editSummary,
 minor:true,
 watchlist:'nochange',
 token:mw.user.tokens.get('csrfToken')
 },
 success:function(){
 console.log('Dummy edit successful');
 addLogEntry('Added dummy edit to article',true);
 checkCompletion();
 },
 error:function(jqXHR,textStatus,errorThrown){
 console.error('Error performing dummy edit:',textStatus,errorThrown);
 addLogEntry('Failed to add dummy edit to article',false);
 checkCompletion();
 }
 });
 },
 error:function(jqXHR,textStatus,errorThrown){
 console.error('Error retrieving page content:',textStatus,errorThrown);
 addLogEntry('Failed to retrieve page content',false);
 checkCompletion();
 }
 });

 if(addTemplate){
 vartalkPageTitle=getTalkPageTitleFrom(pageName);

 $.ajax({
 url:mw.util.wikiScript('api'),
 type:'GET',
 data:{
 format:'json',
 action:'query',
 prop:'revisions',
 rvprop:'content',
 rvslots:'main',
 titles:talkPageTitle
 },
 success:function(data){
 varpages=data.query.pages;
 vartalkPageContent='';
 vartalkPageExists=false;

 for(varpageIdinpages){
 if(!pages.hasOwnProperty(pageId))continue;
 if(pages[pageId].missing===''){
 talkPageExists=false;
 }elseif(pages[pageId].revisions){
 talkPageExists=true;
 varrev=pages[pageId].revisions[0];
 talkPageContent=(rev&&rev.slots&&(rev.slots.main['*']||rev.slots.main['content']))||'';
 }
 }

 if(talkPageExists){
 varexistingTemplateMatch=talkPageContent.match(/{{\s*(?:translationsource|translated article|translated|tradotto da|traducido ref|translated page|překlad|translated from)\s*(\|.*)?}}/i);

 if(existingTemplateMatch){
 console.log('Template already present');
 addLogEntry('{{Translated page}} already exists on talk page',true);
 checkCompletion();
 return;
 }

 if(talkPageContent.includes('{{WikiProject banner shell')){
 varbannerShellEndIndex=talkPageContent.lastIndexOf('}}');
 if(bannerShellEndIndex!==-1){
 talkPageContent=talkPageContent.slice(0,bannerShellEndIndex+2)+
 '\n{{translated page|'+langCode+'|'+articleName+'|small=no}}'+
 talkPageContent.slice(bannerShellEndIndex+2);
 console.log('Added {{translated page}} inside banner shell');
 }else{
 talkPageContent+='\n{{translated page|'+langCode+'|'+articleName+'|small=no}}';
 }
 }else{
 talkPageContent+='\n{{translated page|'+langCode+'|'+articleName+'|small=no}}';
 console.log('Added {{translated page}} to talk page');
 }

 $.ajax({
 url:mw.util.wikiScript('api'),
 type:'POST',
 data:{
 format:'json',
 action:'edit',
 title:talkPageTitle,
 summary:'Adding {{translated page}} attribution ([[User:CFA/scripts/AttributeTranslation|AT]])',
 text:talkPageContent,
 token:mw.user.tokens.get('csrfToken')
 },
 success:function(){
 console.log('Talk page updated');
 addLogEntry('Added {{translated page}} to talk page',true);
 checkCompletion();
 },
 error:function(jqXHR,textStatus,errorThrown){
 console.error('Error updating talk page:',textStatus,errorThrown);
 addLogEntry('Failed to add template to talk page',false);
 checkCompletion();
 }
 });
 }else{
 $.ajax({
 url:mw.util.wikiScript('api'),
 type:'POST',
 data:{
 format:'json',
 action:'edit',
 title:talkPageTitle,
 summary:'Adding {{Translated page}} attribution ([[User:CFA/scripts/AttributeTranslation|AT]])',
 text:'{{translated page|'+langCode+'|'+articleName+'|small=no}}',
 token:mw.user.tokens.get('csrfToken')
 },
 success:function(){
 console.log('Talk page created and template added');
 addLogEntry('Added {{translated page}} to talk page',true);
 checkCompletion();
 },
 error:function(jqXHR,textStatus,errorThrown){
 console.error('Error creating talk page:',textStatus,errorThrown);
 addLogEntry('Failed to create talk page',false);
 checkCompletion();
 }
 });
 }
 },
 error:function(jqXHR,textStatus,errorThrown){
 console.error('Error retrieving talk page:',textStatus,errorThrown);
 addLogEntry('Failed to retrieve talk page',false);
 checkCompletion();
 }
 });
 }

 selectedContributors.forEach(function(contributor){
 notifyContributor(contributor,langCode,articleName);
 });

 functionnotifyContributor(contributor,langCode,articleName){
 varsubst="subst:";
 varsig="~~"+"~~";
 varnotificationMessage=`{{${subst}uw-translation|1=${langCode}:${articleName}|to=${pageTitle}}} ${sig}`;

 $.ajax({
 url:mw.util.wikiScript('api'),
 type:'POST',
 data:{
 format:'json',
 action:'edit',
 title:'User talk:'+contributor,
 summary:'Adding unattributed translation notice ([[User:CFA/scripts/AttributeTranslation|AT]])',
 section:'new',
 watchlist:'nochange',
 sectiontitle:'Unattributed translations',
 text:notificationMessage,
 token:mw.user.tokens.get('csrfToken')
 },
 success:function(){
 console.log('Notification sent to user talk page');
 addLogEntry(`Warned user (${contributor})`,true);
 checkCompletion();
 },
 error:function(jqXHR,textStatus,errorThrown){
 console.error('Error sending notification:',textStatus,errorThrown);
 addLogEntry(`Failed to warn user (${contributor})`,false);
 if(confirm("Could not notify contributor. Retry?")){
 notifyContributor(contributor,langCode,articleName);
 }else{
 checkCompletion();
 }
 }
 });
 }
 }

 functiongetPageContributors(title,callback){
 $.ajax({
 url:mw.util.wikiScript('api'),
 type:'GET',
 data:{
 format:'json',
 action:'query',
 prop:'revisions',
 rvprop:'user',
 titles:title,
 rvlimit:'max',
 rvdir:'newer'
 },
 success:function(data){
 varpages=data.query.pages;
 varcontributors=[];
 for(varpageIdinpages){
 if(!pages.hasOwnProperty(pageId))continue;
 varrevisions=pages[pageId].revisions||[];
 varcreator=true;
 revisions.forEach(function(revision){
 if(revision.user&&revision.user!==''){
 varidx=contributors.findIndex(function(item){
 returnitem.username===revision.user;
 });
 if(idx===-1){
 contributors.push({username:revision.user,edits:1,isCreator:creator});
 }else{
 contributors[idx].edits++;
 }
 creator=false;
 }
 });
 }
 callback(contributors);
 },
 error:function(jqXHR,textStatus,errorThrown){
 console.error('Error retrieving page contributors:',textStatus,errorThrown);
 }
 });
 }

 functionaddButtonToToolbar(){
 varallowedNamespaces=[0,118];
 varcurrentNamespace=mw.config.get('wgNamespaceNumber');

 if(allowedNamespaces.includes(currentNamespace)){
 mw.util.addPortletLink(
 'p-cactions',
 '#',
 'Translation attribution',
 'ca-translation-attribution',
 'AttributeTranslation',
 null,
 null
 );

 document.getElementById('ca-translation-attribution').addEventListener('click',function(e){
 e.preventDefault();
 getPageContributors(pageTitle,function(contributors){
 createInputGUI(contributors);
 });
 });
 }
 }

 addButtonToToolbar();
 })();
 //</nowiki>

AltStyle によって変換されたページ (->オリジナル) /