Aller au contenu

Utilisateur:Utilisateur exemple/User-script manager.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.
//<pre><nowiki>
/*********************************************************************************************************************************************
 *  User-script manager                                                                                                                      *
 * Permet de gérer une liste de scripts à la manière des gadgets mais pour n'importe quelle page                                             *
 *  Pour installer ce gestionnaire :                                                                                                         *
 *  # Copiez cette page dans Utilisateur:<VotreNom>/User-script_manager.js                                                                   *
 *                                                                                                                                           *
 *  # Copiez le code suivant dans la page Utilisateur:<VotreNom>/monobook.js en remplaçant MYNAME par votre pseudo (x2) :                    *
 *                                                                                                                                           *
 * // jncsp-start La section ci-dessous est produite par [[Utilisateur:MYNAME/User-script_manager.js]]                                       *
 * // jncsp-config                                                                                                                           *
 *                                                                                                                                           *
 * document.write('<script type="text/javascript" src="http://www.wiki-donjons-et-dragons.fr' +                                              *
 *                '/index.php?title=Utilisateur:MYNAME/User-script_manager.js&action=raw&ctype=text/javascript"></script>');                 *
 *                                                                                                                                           *
 * // jncsp-end                                                                                                                              *
 *                                                                                                                                           *
 *  #Rechargez le cache de votre navigateur et admirez le résultat                                                                           *
 *                                                                                                                                           *
 *********************************************************************************************************************************************/

//////////////////////////////////////////////// PARTIE PERSONNALISABLE /////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////// PARAMETRES --------------
 
cspEntryPage = 'Utilisateur:' + mw.config.get('wgUserName').replace(/ /,"_") + '/monobook.js';                                                       //Page où le script s'active
cspMainScript = 'Utilisateur:' + mw.config.get('wgUserName').replace(/ /,"_") + '/User-script_manager.js';                                           //Page où est copié le code du script manager
cspScriptRepos = 'Utilisateur:Dr_Brains/';                                                                                          //Répertoire par défaut des scripts personnels
cspScriptLinks = 'http://fr.wikipedia.org/wiki/Utilisateur:Dr_Brains/'                                                              //Url du répertoire par défaut
cspSummary = 'Mise à jour avec [[Utilisateur:' + mw.config.get('wgUserName').replace(/ /,"_") + '/User-script_manager.js]]';                         //Résumé de modification

cspStartComment2 = ' La section ci-dessous est produite par le script : [[Utilisateur:' + mw.config.get('wgUserName') + '/User-script manager.js]]'; //Commentaire inséré au début du monobook.js
 
////////////////////////////// AFFICHAGE -------------------
cspFragments = [

/********** Liste des scripts ****************************************************************************************************************
 *                                                                                                                                           *
 * Liste des fichiers JavaScript :                                                                                                           *
 *   id   = un identifiant unique, généralement le nom de la fonction principale                                                             *
 *   type = 0 (défaut): Le script sera entièrement recopié dans la page. (Peut se révéler problématique avec certains caractères spéciaux.)  *
 *          1: Le script sera inclus par un élément <script> (solution préférable)                                                           *
 *          2: Titre de chapitre                                                                                                             *
 *   page = nom de la page où le script à inclure est stocké                                                                                 *
 *   rev  = numéro de révision de la page (si inclusion d'une page archivée)                                                                 *
 *   deps = liste des dépendances, à ignorer si il n'y en a pas                                                                              *
 *   desc = description du script                                                                                                            *
 *                                                                                                                                           *
 *********************************************************************************************************************************************/


{ desc: 'Scripts en test', type: 2 },

  { id: 'setupBoites', 
    page: cspScriptRepos + 'Boites.js', 
    type: 1, 
    desc: '<a href=http://fr.wikipedia.org/wiki/Utilisateur:Dr_Brains/Boites.js>Boites</a>' 
  },
  { id: 'setupMagicSidebox', 
    page: cspScriptRepos + 'MagicSidebox.js', 
    type: 1, 
    desc: '<a href=http://fr.wikipedia.org/wiki/Utilisateur:Dr_Brains/MagicSidebox.js>MagicSidebox</a>' 
  },

{ desc: 'Scripts persos', type: 2 },

  { id: 'setupCollapseSidebox', 
    page: cspScriptRepos + 'CollapseSidebox.js', 
    type: 1, 
    desc: '<a href=http://fr.wikipedia.org/wiki/Utilisateur:Dr_Brains/CollapseSidebox.js>CollapseSidebox</a>' 
  },
  { id: 'setupEvaluation', 
    page: cspScriptRepos + 'Evaluation.js', 
    type: 1, 
    desc: '<a href=http://fr.wikipedia.org/wiki/Utilisateur:Dr_Brains/Evaluation.js>Evaluation</a>' 
  },
  { id: 'setupGoogle', 
    page: cspScriptRepos + 'Google.js', 
    type: 1, 
    desc: '<a href=http://fr.wikipedia.org/wiki/Utilisateur:Dr_Brains/Google.js>Google</a>' 
  },
  { id: 'setupfavoris', 
    page: cspScriptRepos + 'favoris.js', 
    type: 1, 
    desc: '<a href=http://fr.wikipedia.org/wiki/Utilisateur:Dr_Brains/favoris.js>favoris</a>' 
  }, 
  { id: 'setupFullScreen', 
    page: cspScriptRepos + 'FullScreen.js', 
    type: 1, 
    desc: '<a href=http://fr.wikipedia.org/wiki/Utilisateur:Dr_Brains/FullScreen.js>Fullscreen</a>' 
  },
  { id: 'setupSuiviCat', 
    page: cspScriptRepos + 'SuiviCat.js', 
    type: 1,
    desc: '<a href=http://fr.wikipedia.org/wiki/Utilisateur:Dr_Brains/SuiviCat.js>SuiviCat</a>' 
  },
  { id: 'setupmyName', 
    page: cspScriptRepos + 'myName.js', 
    type: 1, 
    desc: '<a href=http://fr.wikipedia.org/wiki/Utilisateur:Dr_Brains/myName.js>myName</a>' 
  },
  { id: 'setupCacheLiens', 
    page: cspScriptRepos + 'CacheLiens.js', 
    type: 1, 
    desc: '<a href=http://fr.wikipedia.org/wiki/Utilisateur:Dr_Brains/CacheLiens.js>CacheLiens</a>' 
  },
  { id: 'setupPopups', 
    page: cspScriptRepos + 'Popups.js', 
    type: 1, 
    desc: '<a href=http://fr.wikipedia.org/wiki/Utilisateur:Dr_Brains/Popups.js>Popups</a>' 
  },


 
{ desc: 'Générer le script', type: 2 },
 
///////////////////////////////////////////////////////// FIN DE LA PARTIE PERSONNALISABLE //////////////////////////////////////////////////////////////////////////// 
];

cspStartComment = '// jncsp-start';
cspConfigComment = '// jncsp-config';
cspEndComment = '// jncsp-end';

//    if(mw.config.get('wgPageName').match('Utilisateur:' + mw.config.get('wgUserName').replace(/ /,"_") + '/monobook.js') && mw.config.get('wgAction')=="view"){
 
/* Construct an XMLHttpRequest */
 
function cspConstructHttpRequest()
{
   var res;
 
   // Copied from http://developer.mozilla.org/en/docs/AJAX:Getting_Started
   if (window.XMLHttpRequest) { // Mozilla, Safari, ...
      res = new XMLHttpRequest();
   } else if (window.ActiveXObject) { // IE
      res = new ActiveXObject("Microsoft.XMLHTTP");
   }
   return res;
}
 
function getXmlObj(req) {
   if (req.responseXML && req.responseXML.documentElement) 
      return req.responseXML;
 
   // Note: this doesn't work in konqueror, and the natural fix
   // var doc=document.implementation.createDocument(); doc.loadXML(req.responseXML)
   // results in a segfault :-(
   try {
      var doc = new ActiveXObject("Microsoft.XMLDOM");
      doc.async = "false";
      doc.loadXML(req.responseText);
   } 
   catch (err) {
      return null;
   }
 
   return doc;
}
 
/* Checks whether the request has finished successfully
   req = XMLHtmlRequest 
   Returns true or false */
 
function cspRequestDone(req)
{
   if (req.readyState != 4) {
      // still not ready
      return false;
   } 
   if (window.http_request.status != 200) {
      alert('There was a problem with the request.');
      return false;
   }
   return true;
}
 
// Source: http://www.albionresearch.com/misc/urlencode.php
function URLEncode( plaintext ) 
{
   // The Javascript escape and unescape functions do not correspond
   // with what browsers actually do...
   var SAFECHARS = "0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "-_.!~*'()";
   var HEX = "0123456789ABCDEF";
   var encoded = "";
   for (var i = 0; i < plaintext.length; i++ ) {
      var ch = plaintext.charAt(i);
      if (ch == " ") {
	 encoded += "+";				// x-www-urlencoded, rather than %20
      } else if (SAFECHARS.indexOf(ch) != -1) {
	 encoded += ch;
      } else {
	 var charCode = ch.charCodeAt(0);
	 if (charCode > 255) {
	    alert( "Unicode Character '" + ch + "' cannot be encoded using standard URL encoding.\n" +
		   "(URL encoding only supports 8-bit characters.)\n" + 
		   "A space (+) will be substituted." );
	    encoded += "+";
	 } else {
	    encoded += "%";
	    encoded += HEX.charAt((charCode >> 4) & 0xF);
	    encoded += HEX.charAt(charCode & 0xF);
	 }
      }
   } // for
   return encoded;
}
 
/* Returns dictionary with form data */
 
function cspFormData(form) {
   var res = new Object();
   for (var i=0; i<form.elements.length; ++i) {
      var el = form.elements[i];
      var data;
 
      if (!el.name)
	 continue;
      if (el.tagname && el.tagname == 'textarea')
	 data = el.childNodes[0].data;
      else if (el.checked)
	 data = ((el.checked == 'checked') ? 'on' : 'off');
      else if (el.value)
	 data = el.value;
      else
	 continue;
 
      res[el.name] = data;
   }
   return res;
}
 
/* Replace body contents by x */
 
function cspReplacePage(x) 
{
   var el = document.getElementById('bodyContent').childNodes[0];
   while (el.nextSibling) {
      el = el.nextSibling;
      if (el.tagName && el.tagName.toLowerCase() == 'p') 
         break;
   }
   el.parentNode.replaceChild(x, el);
}
 
/* Returns string with HTML Form in which the user can set their preferences */
 
function cspGetForm(oldconfig)
{
   var f, i, res;
   res = '<p>Page gérée par <a href=http://fr.wikipedia.org/wiki/' + cspMainScript + '>' + cspMainScript +'</a> <br> <br>Sélectionner les scripts à ajouter au style Monobook.</p>\n'
      + '<form>\n';
   for (i=0; i<cspFragments.length; i++) {
      f = cspFragments[i];
      if (!f.desc) continue;
      if (f.type == 2) {
	 /* a chapter heading */
	 if (i != 0) res += '</p>\n';
	 res += '<h2><span class="mw-headline">' + f.desc
	    + '</span></h2>\n'
	    + '<p>\n';
      } else {
	 /* a script fragment */
	 res += '<input type="checkbox" name="' + f.id + '" ';
	 if (oldconfig.indexOf(f.id) != -1)
	    res += 'checked ';
	 res += '/> ' + f.desc + '<br/>\n';
      }
   }
   res += '<input type="button" onclick="cspProcessForm();" value="OK" /></p>\n'
      + '</form>\n';
   return res;
}
 
/* Returns index of fragment with given id in fraglist, or -1 if it is not there. */
 
function cspFindFragment(id, fraglist)
{
   for (var n=0; n<fraglist.length; n++) {
      if (fraglist[n].id == id)
	 return n;
   }
   return -1;
}
 
/* Add fragment f to the list of fragments to be downloaded */
 
function cspAddFragment(f)
{
   var d, pos, i, tmp;
 
   /* If f is already on the list, we're done */
   if (cspFindFragment(f.id, window.fragments) != -1)
      return; 
 
   pos = -1;
 
   if (f.deps) {
      /* Add all dependencies */
      for (i=0; i<f.deps.length; i++) {
	 tmp = cspFindFragment(f.deps[i], cspFragments);
	 if (tmp == -1)
	    alert("Error in cspAddFragment: Cannot find " + f.deps[i]);
	 cspAddFragment(cspFragments[tmp]);
      }
 
      /* Find the last dependency */
      for (i=0; i<f.deps.length; i++) {
	 tmp = cspFindFragment(f.deps[i], window.fragments);
	 if (tmp>pos) 
	    pos = tmp;
      }
   }
 
   /* Add f after all its dependencies */
   window.fragments.splice(pos+1, 0, f);
}
 
/********** Main script **********/
 
/* This function is called if the user visits the entry page. */
 
function clientSidePreferencesLoadFunction() 
{
   var p = document.createElement("p");
   p.innerHTML = "<p>Veuillez patienter pendant l'analyse de votre configuration …</p>";
   cspReplacePage(p);
 
   window.http_request = cspConstructHttpRequest();
   window.http_request.onreadystatechange = cspReceivedOldScript;
   var url = mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/index.php?title=User:' + mw.config.get('wgUserName') + '/monobook.js&action=raw';
   window.http_request.open('GET', url, true);
   window.http_request.send(null);
}
 
/* This function is called when the old user script is received. */
 
function cspReceivedOldScript() 
{
   if (!cspRequestDone(window.http_request))
      return;
   window.oldscript = window.http_request.responseText;
 
   var oldconfig = [];
   var i = window.oldscript.indexOf(cspConfigComment);
   if (i != -1) {
      var i2 = window.oldscript.indexOf('\n', i);
      var oldconfig = window.oldscript.substring(i+cspConfigComment.length+1, i2).split(' ');
   }
 
   cspDisplayForm(oldconfig);
}
 
/* Creates and display the HTML form. */
 
function cspDisplayForm(oldconfig)
{
   var cspForm = document.createElement("form");
   cspForm.innerHTML = cspGetForm(oldconfig);
   cspForm.name = 'cspForm';
   cspReplacePage(cspForm);
}
 
/* This function is called when the user presses the "Generate script" button. 
   It collects all fragments that should be downloaded in window.fragments
   and starts building the new script in window.newscript */
 
function cspProcessForm() 
{
   window.fragments = new Array();
   var newconfig = '';
 
   for (var i=0; i<cspFragments.length; i++) {
      var f = cspFragments[i];
      if (f.desc && f.type != 2 && document.cspForm[f.id].checked) {
	 cspAddFragment(f);
	 newconfig += ' ' + f.id;
      }
   }
 
   window.newscript = '';
 
   var i = window.oldscript.indexOf(cspStartComment);
   if (i != -1) 
      window.newscript += window.oldscript.substr(0, i)
 
   window.newscript += cspStartComment + cspStartComment2 + '\n';
   window.newscript += cspConfigComment + newconfig + '\n\n';
 
   var s = 'document.write(\'<script type="text/javascript" src="' + mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '\' + \n'
      + '               \'/index.php?title=' + cspMainScript + '&action=raw&ctype=text/javascript"></script>\'); \n';
 
   window.newscript += s;
 
   window.bottom = document.cspForm;
   cspGetFragments();
}
 
/* Go through the fragments listed in window.fragments and 
   build window.newscript */
 
function cspGetFragments() 
{
   if (window.fragments.length == 0) {
      cspFinalizeScript();
      return;
   } 
 
   var f = window.fragments[0];
   if (f.type == 1) 
      cspImportFragment(f);
   else
      cspDownloadFragment(f) 
}
 
/* Download a JavaScript fragment to be included in the user script */
 
function cspDownloadFragment(f)
{
   var msg = document.createTextNode('Chargement de ' + f.page + ' ...');
   window.bottom = window.bottom.parentNode.insertBefore(msg, bottom.nextSibling);
 
   window.http_request = cspConstructHttpRequest();
   window.http_request.onreadystatechange = cspReceivedFragment;
   var url = 'http://www.wiki-donjons-et-dragons.fr/index.php?title=' + f.page
             + '&oldid=' + f.rev + '&action=raw&ctype=text/javascript';
   window.http_request.open('GET', url, true);
   window.http_request.send(null);
}
 
/* Callback for HTTP request initiated in cspDownloadFragment() */
 
function cspReceivedFragment() 
{
   if (!cspRequestDone(window.http_request))
      return;
 
   var msg = document.createTextNode(' OK');
   window.bottom = window.bottom.parentNode.insertBefore(msg, bottom.nextSibling);
   window.bottom = window.bottom.parentNode.insertBefore(document.createElement('BR'), bottom.nextSibling);
 
   /* Chop off preamble and postamble */
   var txt = window.http_request.responseText;   
 
   /* First look for the script between "// <pre><nowiki>"
      and "// </ nowiki></ pre>" */
   var tmp = /\/\/[ ]*<pre><nowiki>[ ]*\n/.exec(txt);
   if (tmp)
      txt = txt.slice(tmp.index + tmp[0].length);
   tmp = /\/\/[ ]*<\/nowiki><\/pre>[ ]*(\n|$)/.exec(txt);
   if (tmp)
      txt = txt.slice(0, tmp.index);
   else {
      /* Otherwise, see if it is between "/ * <pre> * /" 
	 and "/ * </ pre> * /" (without the spaces) */
      tmp = /\/\*.*<pre>.*\*\/\n/.exec(txt);
      if (tmp)
	 txt = txt.slice(tmp.index + tmp[0].length);
      tmp = /\/\*.*<\/pre>.*\*\/(\n|$)/.exec(txt);
      if (tmp)
	 txt = txt.slice(0, tmp.index);
      else {
	 /* Otherwise, see if it is between "<pre>" and "</ pre>" */
	 tmp = /<pre>[ ]*\n/.exec(txt);
	 if (tmp)
	    txt = txt.slice(tmp.index + tmp[0].length);
	 tmp = /<\/pre>[ ]*(\n|$)/.exec(txt);
	 if (tmp)
	    txt = txt.slice(0, tmp.index);
      }
   }
 
   window.newscript += '\n// From [[' + (window.fragments[0].page).replace('_', ' ')
                        + ']], revision ' + window.fragments[0].rev + '\n\n' + txt + '\n';
   window.fragments = window.fragments.slice(1);
   cspGetFragments();
}
 
/* Import JavaScript using a <script> tag */
 
function cspImportFragment(f)
{
   var msg = document.createTextNode('Importation de ' + f.page);
   window.bottom = window.bottom.parentNode.insertBefore(msg, bottom.nextSibling);
   window.bottom = window.bottom.parentNode.insertBefore(document.createElement('BR'), bottom.nextSibling);
 
   window.newscript += '\n// Import [[' + (window.fragments[0].page).replace('_', ' ') + ']]\n\n'
      + 'document.write(\'<script type="text/javascript" src="' + mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '\' + \n'
      + '               \'/index.php?title=' + f.page + '&action=raw&ctype=text/javascript"></script>\'); \n';
 
   window.fragments = window.fragments.slice(1);
   cspGetFragments();
}
 
function cspFinalizeScript()
{
   window.newscript += '\n' + cspEndComment;
 
   var i = window.oldscript.indexOf(cspEndComment);
   if (i != -1) 
      window.newscript += window.oldscript.substr(i+cspEndComment.length)
 
   cspLoadEditPage();
}
 
function cspLoadEditPage() 
{
   var msg = document.createTextNode('Chargement de votre script ...');
   window.bottom = window.bottom.parentNode.insertBefore(msg, bottom.nextSibling);
 
   window.http_request = cspConstructHttpRequest();
   window.http_request.overrideMimeType('text/xml');
   window.http_request.onreadystatechange = cspReceivedEditPage;
   var url = mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/index.php?title=User:' + mw.config.get('wgUserName') + '/monobook.js&action=edit';
   window.http_request.open('GET', url, true);
   window.http_request.send(null);
}
 
function cspReceivedEditPage() 
{
   if (!cspRequestDone(window.http_request))
      return;
 
   var doc = window.http_request.responseXML;
   var editform = doc.getElementById('editform');
   var data = cspFormData(editform);
   data['wpTextbox1'] = window.newscript;
   data['wpSummary'] = cspSummary;
   data['wpMinoredit'] = 'on';
   data['wpPreview'] = null;
   data['wpDiff'] = null;
 
   var msg = document.createTextNode(' Sauvegarde de votre script ...');
   window.bottom = window.bottom.parentNode.insertBefore(msg, bottom.nextSibling);
 
   window.http_request = cspConstructHttpRequest();
   window.http_request.overrideMimeType('text/xml');
   window.http_request.onreadystatechange = cspEditPageSaved;
   var url = mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/index.php?title=User:' + mw.config.get('wgUserName') + '/monobook.js&action=submit';
   window.http_request.open('POST', url, true);
   window.http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 
   sendMe = '';
   for (var name in data) {
      if (data[name]) {
	 if (sendMe.length > 0) 
	    sendMe += '&';
	 sendMe += URLEncode(name) + '=' + URLEncode(data[name]);
      }
   }
   window.http_request.send(sendMe);
}
 
function cspEditPageSaved() 
{
   if (!cspRequestDone(window.http_request))
      return;
 
   var msg = document.createTextNode(' OK');
   window.bottom = window.bottom.parentNode.insertBefore(msg, bottom.nextSibling);
   window.bottom = window.bottom.parentNode.insertBefore(document.createElement('BR'), bottom.nextSibling);
   window.location.reload();
}
 
$(clientSidePreferencesLoadFunction);
//} 
//</nowiki></pre>