Aller au contenu

Utilisateur:JoKerozen/modif.js

Une page de Wikipédia, l'encyclopédie libre.
Note : après avoir enregistré la page, vous devrez forcer le rechargement complet du cache de votre navigateur pour voir les changements.

Mozilla / Firefox / Konqueror / Safari : maintenez la touche Majuscule (Shift) en cliquant sur le bouton Actualiser (Reload) ou pressez Maj-Ctrl-R (Cmd-R sur Apple Mac) ;

Firefox (sur GNU/Linux) / Chrome / Internet Explorer / Opera : maintenez la touche Ctrl en cliquant sur le bouton Actualiser ou pressez Ctrl-F5.
//<source lang="javascript" line>
/*
 * Scriptus
 *
 * La fonction Scriptus sert à rédiger sur wikipédia de manière naturelle, 
 * par simple doubleclic et confimation de sauvegarde. 
 * La définition de ce script se trouve ici : 
 * http://fr.wikipedia.org/wiki/Wikip%C3%A9dia:Brouillons/interface_ajax
 *
 * Le code du script est librement inspiré du système de modification-inline de Olivier Lance
 * http://olance.developpez.com/articles/web/javascript/modification-inline/
 *
 * Auteurs : ivo talvet (fr:user:Tavernier) , JoKerozen (fr:user:JoKerozen)
 * Date de dernière révision : 15 octobre 2007
 * copié-collé depuis http://fr.wikipedia.org/w/index.php?title=MediaWiki:JSScripts/Scriptus&oldid=21566322
 */

function Scriptus() {
   if (!mw.config.get('wgIsArticle')) return; //si non editable, sortie
   if (mw.config.get('wgNamespaceNumber')/2 != Math.round(mw.config.get('wgNamespaceNumber')/2)) return; //si impair (discussion), retour
   if (/^Wikipédia:(Le_Bistro|Bulletin_des_administrateurs|Questions_techniques)/.test(mw.config.get('wgPageName'))
       || document.getElementById('transformeEnPageDeDiscussion')
      ) return; //cas exceptionnels de discussion dans ns pair

   loadEventsScriptus();
}


function loadEventsScriptus() {

   var intro = $(".firstHeading")[0];
   intro.className = "mw-headline firstHeading"; //cohérence

   $(".mw-headline").each(function (_, section) {
       if (section.className == "mw-headline firstHeading") {
           var numSection = 0; //firstHeading
       } 
       else {
           var hrefSection = $(section).parent().find('.editsection a').attr('href');
           var numSection = hrefSection.replace(/section=([0-9]+)/g, '$1');
       }
       section.addEventListener("dblclick", findBlocScriptus(numSection), false);
   });
}


function findBlocScriptus(numSection) 
{
    return function()
    {
    if (document.getElementsByTagName('textarea').length) return;

    document.ou = numSection;


    var headers = new Array();
    headers['Cache-Control'] = 'no-cache, must-revalidate';
    headers['Pragma'] = 'no-cache';

alert(fetchTimezone());


    // quitte a charger la page d'edit, autant le faire ici et récupérer wpTextbox1, qui normalement est a jour 

    if (document.ou == 0) {
    var demandeSection = ''
    } 
    else {
    var demandeSection = '&section=' + document.ou
    }


    var editFormSeek = wpajaxScriptus.http({ url: mw.config.get('wgServer') + mw.config.get('wgScriptPath')
                               +'/index.php?title='
                               + encodeURIComponent(mw.config.get('wgPageName'))
                               + '&action=raw&maxage=0'
                               + demandeSection,
                           async: false,
                           headers: headers,
                           });



    afficheBlocScriptus(editFormSeek);

    };
}


function afficheBlocScriptus(editFormSeek) {

    //var parser = new DOMParser();

    //var doc = parser.parseFromString(editFormSeek.responseText, 'application/xhtml+xml');

    if (document.ou == 0) {
        var bloc = $('.mw-headline.firstHeading')[0];
    } 
    else {
        var bloc = $('.mw-headline')[document.ou].parentNode;
    }

    var form = document.createElement("form");
    form.className = 'ajaxedit';
    form.name = 'ajaxEditForm';
    form.method = 'get';
    form.action = "javascript:envoye2BlocScriptus();"; //redondant ? (non en cas de touche entree sur le input de résumé) 

    var wpTextbox1 = editFormSeek.responseText;

    var textarea = document.createElement("textarea");
    textarea.className = "ajaxTextarea";
    var lines = wpTextbox1.split(/\n/).length;
    var nbchars = wpTextbox1.length;

    textarea.appendChild(document.createTextNode(editFormSeek.responseText));
    form.appendChild(textarea);

    var summary = document.createElement("input");
    summary.type = "Text";
    summary.name = "wpSummary";
    summary.id = "wpSummary"
    summary.value="Veuillez résumer vos modifications"
    form.appendChild(summary);

    var save = document.createElement("input");
    save.type = "button";
    save.value = "Envoyer"
    form.appendChild(save);

    var preview = document.createElement("input");
    preview.type = "button";
    preview.value = "Prévisualisation"
    form.appendChild(preview);

    var annuler = document.createElement("input");
    annuler.type = "button";
    annuler.value = "Annuler"
    form.appendChild(annuler);




    bloc.appendChild(form); 

    var largeur = form.offsetWidth;
    var colones = largeur*10/75;
    var nblines = nbchars/colones+lines;
    textarea.rows = nblines;

    save.addEventListener("click", envoye2BlocScriptus, false);
    annuler.addEventListener("click", annuleScriptus, false);
    preview.addEventListener("click", previsualisationScriptus, false);
}

function annuleScriptus() {

    if (document.ou == 0) {
        var bloc = $('.mw-headline.firstHeading')[0];
    } 
    else {
        var bloc = $('.mw-headline')[document.ou].parentNode;
    }

    var form = $('.ajaxedit')[0]
    if (document.getElementById('wikiPreview')) {
        var oldpreview = document.getElementById('wikiPreview').parentNode.removeChild(document.getElementById('wikiPreview'))
    }
    var oldform = bloc.removeChild(form);


}
/*</source>

== Après affichage ==

<source lang="javascript" line>*/

function envoye2BlocScriptus() {

    var wpTextbox1 = encodeURIComponent(document.getElementsByTagName('textarea')[0].value);
    var wpSection = document.ou
    var wpSummary = encodeURIComponent(document.getElementById('wpSummary').value);
    if (wpSummary == encodeURI("Veuillez résumer vos modifications")) wpSummary = ""; 

    // recuperation des champ hidden

    //var wpEdittime = document.getElementById('hiddenEdittime').value;
    //var wpEditToken = document.getElementById('hiddenEditToken').value;
    //var wpStarttime = document.getElementById('hiddenStarttime').value;


var asdfgh = wpajaxScriptus.http({ url: mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/api.php?action=query&prop=info&titles=' + mw.config.get('wgPageName') + '&intoken=edit&format=xml', async:false });
var parser = new DOMParser();
var doc = parser.parseFromString(asdfgh.responseText, 'text/xml');

//alert("api editoken : " + doc.getElementsByTagName('page')[0].getAttribute('edittoken'));
//alert("editform wpEditToken : " + wpEditToken);


edittime = doc.getElementsByTagName('page')[0].getAttribute('touched');
ed1 = edittime.split('-')[0]+edittime.split('-')[1]+edittime.split('-')[2];
ed2 = ed1.split('T')[0]+ed1.split('T')[1];
ed3 = ed2.split(':')[0]+ed2.split(':')[1]+ed2.split(':')[2];
edfin = ed3.split('Z')[0]

//alert("api edittime" + edfin)
//alert("editform wpEdittime : " + wpEdittime);

//alert("editform wpStarttime : " + wpStarttime);
date = new Date();
//alert("starttime en fonction de lobjet Date() : " + getTimeStampScriptus(date) );


    var wpEdittime = edfin;
    var wpEditToken = encodeURIComponent(doc.getElementsByTagName('page')[0].getAttribute('edittoken'));
    var wpStarttime = getTimeStampScriptus(date);


    if (document.ou == 0) {
    var Section_editee = ''
    } else {
    var Section_editee = '&wpSection=' + wpSection
    }

    if (document.getElementById('ca-unwatch')) {
      var suivi = '&wpWatchthis=1';
    } else {
      var suivi = '';
    }

    var headers = new Array();
    headers['Content-Type'] = 'application/x-www-form-urlencoded';
    headers['Cache-Control'] = 'no-cache, must-revalidate';


    document.HttpWPedit = wpajaxScriptus.http({ url: mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/index.php?title=' 
                                 + encodeURIComponent(mw.config.get('wgPageName')) 
                                 + '&action=submit',
                          method: "POST", 
                          headers: headers,
                          async: false,
                          data: 'wpSave=1&wpTextbox1=' + wpTextbox1 
                                + '&wpStarttime=' + wpStarttime 
                                + '&wpEdittime=' + wpEdittime
                                + '&wpEditToken=' + wpEditToken 
                                + Section_editee
                                + suivi
                                + '&wpSummary=' + wpSummary + encodeURIComponent(' (mpa)')}); 
    apresModifScriptus();
}



function previsualisationScriptus() {

    if (document.getElementById('wikiPreview')) {
        var oldpreview = document.getElementById('wikiPreview').parentNode.removeChild(document.getElementById('wikiPreview'));
    }

    var wpTextbox1 = encodeURIComponent(document.getElementsByTagName('textarea')[0].value);
    var wpSection = document.ou
    var wpSummary = encodeURIComponent(document.getElementById('wpSummary').value);
    if (wpSummary == encodeURI("Veuillez résumer vos modifications")) wpSummary = ""; 

    // recuperation des champ hidden

    var wpEdittime = document.getElementById('hiddenEdittime').value;
    var wpEditToken = document.getElementById('hiddenEditToken').value;
    var wpStarttime = document.getElementById('hiddenStarttime').value;

    if (document.ou == 0) {
    var Section_editee = ''
    } else {
    var Section_editee = '&wpSection=' + wpSection
    }

    if (document.getElementById('ca-unwatch')) {
      var suivi = '&wpWatchthis=1';
    } else {
      var suivi = '';
    }

    var headers = new Array();
    headers['Content-Type'] = 'application/x-www-form-urlencoded';
    headers['Cache-Control'] = 'no-cache, must-revalidate';


    document.HttpWPpreview = wpajaxScriptus.http({ url: mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/index.php?title=' 
                                 + encodeURIComponent(mw.config.get('wgPageName')) 
                                 + '&action=submit',
                          method: "POST", 
                          headers: headers,
                          async: false,
                          data: 'wpSave=1&wpTextbox1=' + wpTextbox1 
                                + '&wpStarttime=' + wpStarttime 
                                + '&wpEdittime=' + wpEdittime
                                + '&wpEditToken=' + wpEditToken 
                                + Section_editee
                                + '&wpPreview=Prévisualisation'
                                + suivi
                                + '&wpSummary=' + wpSummary + encodeURIComponent(' (mpa)')});

    var parser = new DOMParser();

    var previewRetour = parser.parseFromString(document.HttpWPpreview.responseText, 'application/xhtml+xml');
    var previewHtml = previewRetour.getElementById('wikiPreview');
    var previewDiv = document.createElement("div");
    previewDiv = previewHtml;

    var titre = previewDiv.getElementsByTagName('h2')[0];

    var Aretirer = previewDiv.getElementsByTagName('div')[0];
    previewDiv.removeChild(Aretirer);

    var form = $('.ajaxedit')[0];
 
    previewDiv = form.parentNode.parentNode.insertBefore(previewDiv, form.parentNode.nextSibling);
    previewDiv.style.border = "2px solid #FF8080";
    previewDiv.style.backgroundColor = "#FCFFE5";
    titre.style.color = "#FF8080";

    var fermeturePreview = document.createElement("span");
    fermeturePreview.style.fontSize = "xx-small";
    fermeturePreview.style.fontWeight = "normal";
    fermeturePreview.style.cssFloat = "none";
    fermeturePreview = titre.appendChild(fermeturePreview);
    fermeturePreview.innerHTML = '<a href="javascript:var temporaire = document.getElementById(\'wikiPreview\').parentNode.removeChild(document.getElementById(\'wikiPreview\'));" title="Fermer la prévisualisation">fermer</a>'; //virer le innerHTML

}

function apresModifScriptus() {

    annuleScriptus();

    var parser = new DOMParser();

    var doc = parser.parseFromString(document.HttpWPedit.responseText, 'application/xhtml+xml');
    var entirepage = doc.getElementById('bodyContent');
    var bodycontent = document.getElementById('bodyContent');
    var bodyparent = bodycontent.parentNode;
    var oldBody = bodyparent.removeChild(bodycontent);
    var newbody = document.createElement("div");
    newbody = entirepage;
    bodyparent.appendChild(newbody);

//   for(var i=0; i < onloadFuncts.length; i++) { onloadFuncts[i](); }
// test

	for (var i = 0; i < onloadFuncts.length; i++) {
		onloadFuncts[i]();
	}


}

var wpajaxScriptus = { // depuis http://fr.wikipedia.org/wiki/Utilisateur:EDUCA33E/LiveRC.js
  http: function(bundle) {
    // mandatory: bundle.url
    // optional:  bundle.async
    // optional:  bundle.method
    // optional:  bundle.headers
    // optional:  bundle.data
    // optional:  bundle.onSuccess (xmlhttprequest, bundle)
    // optional:  bundle.onFailure (xmlhttprequest, bundle)
    // optional:  bundle.otherStuff OK too, passed to onSuccess and onFailure
    var xmlhttp;
        try {xmlhttp = new XMLHttpRequest();} catch (e) {xmlhttp = false}
 
    if (xmlhttp) {
      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
          wpajaxScriptus.httpComplete(xmlhttp,bundle);
        }
      }
      xmlhttp.open(bundle.method ? bundle.method : "GET",bundle.url,bundle.async == false ? false : true);
      if (bundle.headers) {
        for (var field in bundle.headers)
          xmlhttp.setRequestHeader(field,bundle.headers[field]);
      }
      xmlhttp.send(bundle.data ? bundle.data : null); 
    }

    return xmlhttp;
  },
 
  httpComplete: function(xmlhttp,bundle) {

    if (xmlhttp.status == 200 || xmlhttp.status == 302) {
      if (bundle.onSuccess) {
        bundle.onSuccess(xmlhttp,bundle);
      } else if (bundle.onFailure) {
      bundle.onFailure(xmlhttp,bundle);
      } else {
      // A activer en debug mode ?
      if (xmlhttp.statusText != "OK") alert(xmlhttp.statusText);
      }
    }
  }
};

// Parser
if (document.implementation.createDocument) {
  var gml_xmlparser = new DOMParser();
}
 
function gml_XMLParse(string) {
  if (document.implementation.createDocument) {
    return gml_xmlparser.parseFromString(string, "text/xml");
  }
  return null;
}

//renvoi le timeStamp depuis l'object date
function getTimeStampScriptus(date)
{
    return date.getFullYear() + 
        toNString(date.getMonth() + 1, 2) + 
        toNString(date.getDate(), 2) + 
        toNString(date.getHours(), 2) + 
        toNString(date.getMinutes(), 2) + 
        toNString(date.getSeconds(), 2)
}

$(Scriptus);
//</source>