2011/04/17

Como usar el DNIe con Firefox 4 en Mac 10.6

This post is in Spanish as it's related only to a problem in Spain with Firefox 4.

DNIe vs Firefox 4

Desde que se lanzó Firefox 4 la gente que usa Mac ha tenido problemas para poder usar el DNIe ya que no permite instalarlo, y si lo tenías instalado con anterioridad no hace nada al intentar acceder a páginas donde lo requieran.

En principio nadie sabía indicar cual era la causa de estos problemas, pero tras crear un ticket en Mozilla respondieron diciendo que el problema es que estabamos intentando usar unas librerías de 32 bits y Firefox 4 se ejecuta por defecto a 64 bits.

Existen los drivers de OpenSC para Mac a 64 bits, pero no sirve de nada instalarlos, ya que los drivers específicos para el DNIe no vienen incluidos y la versión que proporcionan no funcionan con ellos, por lo que tenemos que esperar a que nos publiquen una versión oficial para poder usarlo correctamente.

Solución temporal

Sin embargo, en vez de desinstalar Firefox 4 y volver a la 3.6, podemos configurar fácilmente el ejecutable como indica Willyaranda para que se ejecute a 32 bits y de esa forma sí que podremos instalar la librería necesaria en Firefox y luego usar el DNIe.

Primero vamos a "Aplicaciones" y en el icono de Firefox pinchamos con el botón derecho y escogemos "Obtener información"

En esta ventana se activa la opción de "Abrir en modo de 32 bits"

Y ya está, ahora cuando ejecutemos de nuevo Firefox funcionará en modo de 32 bits y los drivers del DNIe sí que se ejecutarán. Podemos lanzar la web de verificación y nos pedirá que introduzcamos nuestra contraseña.

Si todavía no habíamos instalado el DNIe y esta es la primera vez que lo hacemos, puede pasar que en el paso final tras iniciar de nuevo la sesión en Mac y cuando se lanza automáticamente Firefox, nos diga que no se ha podido instalar el Módulo de seguridad. En ese caso a mi me ha bastado con cerrar Firefox, y al abrirlo de nuevo cargar otra vez el fichero de instalación file:///Library/OpenSC/share/web/instala_modulo_f3.htm y entonces sí que se ha instalado correctamente (tras confirmar los permisos requeridos)

Posibles problemas con los certificados

Otro posible problema con Firefox 4 (pero no exclusivo de Mac ni relacionado exclusivamente con el DNIe) es que al intentar acceder a alguna web con HTTPS nos muestre una ventana de error con este mensaje: "ssl_error_renegotiation_not_allowed"

Dicho problema está explicado por completo en el Wiki de Mozilla: Security:Renegotiation y básicamente se trata de que existe una vulnerabilidad en los protocolos SSL/TLS y desde Firefox 4 han decidido que lo mejor es bloquear dicha vulnerabilidad, e intentar conseguir que todo el mundo actualice sus servidores para evitar el problema.

Por tanto, lo primero que hay que hacer es enviar un correo al contacto de ese sitio web para indicarles la existencia del problema y que deberían solucionarlo lo antes posible. Cuantos más les escribamos, más posibilidades hay de que al fin se decidan a corregirlo aunque no sea más que para no tener que seguir oyéndonos.

Y mientras tanto, pues nosotros podemos hacer unos ajustes en nuestro navegador para poder usar esa web si así lo queremos:

  1. Escribimos about:config en la barra de direcciones y pulsamos enter
  2. Si nos avisa de que podemos estropear algo le decimos que sí, que estamos seguros de lo que queremos hacer.
  3. Escribimos (o pegamos) security.ssl.renego_unrestricted_hosts en el filtro, nos aparecerá la preferencia correspondiente y por defecto como una cadena en blanco.
  4. Le damos a editar y pegamos ahí el dominio donde nos ha dado el error (sin https:// ni las carpetas)

  5. Si hay más de un dominio los separamos con comas.
  6. A continuación filtramos esta otra preferencia security.ssl.treat_unsafe_negotiation_as_broken y la cambiamos a true.

De esta manera ya podremos acceder a ese dominio de forma temporal mientras corrigen los problemas con su servidor y lo dejan bien protegido.

Lo que NO es recomendable es cambiar la configuración de security.ssl.allow_unrestricted_renego_everywhere__temporarily_available_pref ya que eso anula por completo la seguridad y seremos vulverables en cualquier web al problema existente que estaban intentando evitar (es decir, por poder acceder a una web de esta forma se anula la seguridad en todas las webs)

 

2011/04/13

Migrating from FCKeditor is a little easier now

There are tons of site out there that are still using FCKeditor despite the fact that it has been replaced by CKEditor and no work is being done to improve it since long ago.

There are several reasons about that, and one of them is the time cost of upgrading things like the configuration and now there's a little plugin that helps avoid at least one of those problems.

In FCKeditor the definition for Templates (HTML snippets) that the user could insert into the content was available in XML files, but as CKEditor was designed so it could be used in a cross-server environment that meant that the format was changed to JSON in order to load .js files from the server instead of trying to do a XHR that it's quite complex or impossible to do on a foreign server.

But the fact is that most of the people doesn't use CKEditor in such environments and also there are lots of people that have their templates specified in XML files and migrating them to JSON isn't obvious as no tool has been published to carry out that goal. Besides that, I personally find much easier to deal with XML files for the templates instead of the JSON version.

Example of a template in JSON:

   {
    title: 'Image and Title',
    image: 'template1.gif',
    description: 'One main image with a title and text that surround the image.',
    html:
     '<h3>' +
      '<img style="margin-right: 10px" height="100" width="100" align="left"/>' +
      'Type the title here'+
     '</h3>' +
     '<p>' +
      'Type the text here' +
     '</p>'
   },

The same template in XML:

 <Template title="Image and Title" image="template1.gif">
  <Description>One main image with a title and text that surround the image.</Description>
  <Html>
   <![CDATA[
    <img style="MARGIN-RIGHT: 10px" height="100" alt="" width="100" align="left"/>
    <h3>Type the title here</h3>
    Type the text here
   ]]>
  </Html>
 </Template>

In the JSON version you have to use single quotes on each line of the "html" and remember to concatenate everything. In the XML version you just paste whatever you want inside the CDATA comment.

Ok, that's fine. You might like one version or another, but if you want to easily use the XML templates in CKEditor, then upgrade to CKEditor 3.5.3 and add the XmlTemplates plugin.

 

2011/04/09

New beta for WriteArea with CKEditor 3.5.3

Following the release this week of CKEditor 3.5.3, I've updated the WriteArea extension for Firefox to this latest version to include all the bug fixes and enhacements that have been worked on since the last release (check the change log, it's quite a long list as it's usual for every CKEditor release)

In this version, the only patch applied to the core is the latest from this ticket that allows a new button that you can use to switch toolbar on the fly.

The size of the extension has grown again a little due to several languages that have been updated since the previous checks that I did and so I've restored as new they can be correctly used to localize your CKEditor and not have part of the texts in your language and the other half in English.

Direct download link: WriteArea 1.1beta4

2011/03/27

onChange event for CKEditor

It's a somewhat frequent request to see people asking how they can get a notification whenever the content of CKEditor changes.

Some of them are too optimistic:

I've this code <textarea onchange="myfunction()"></textarea> and when I use CKEditor "myfunction" is never called

But most of the people can understand the difference between the original textarea and a CKEditor instance and ask what's the better way to get a notification whenever the content changes, isn't there any built in event for that?

The answer is that no, there's no default event fired whenever something changes, but as I will show here it's quite easy to extend the CKEditor API and generate such event.

Generating a new 'change' event

Although there's no event for "the content has changed" there's something very similar, and that's the Undo system with its saveSnapshot event; whenever something changes it will be called, so we can listen for that event and it will help us greatly with our goal:

       editor.on( 'saveSnapshot', function(e) { somethingChanged(); });

That will take care if the change is something being changed like appying bold or any other style, a new table, pasting, ... it should handle almost everything. But there's one thing that doesn't file a 'saveSnapshot' event, and that's the undo system itself. When Undo or Redo are executed they don't fire that event, so we must listen to them:

        editor.getCommand('undo').on( 'afterUndo', function(e) { somethingChanged(); });
        editor.getCommand('redo').on( 'afterRedo', function(e) { somethingChanged(); });

Ok, Why "something changed"?
Answer: because we are not really sure that something has changed and we aren't really interested to know exactly what has changed, only that something might have changed. Any plugin will fire a "saveSnapshot" before and after any change to work properly, so in our function we will merge all those calls and fire a single event:

        var timer;
        // Avoid firing the event too often
        function somethingChanged()
        {
            if (timer)
                return;

            timer = setTimeout( function() {
                timer = 0;
                editor.fire( 'change' );
            }, editor.config.minimumChangeMilliseconds || 100);
        }

This way the editor will fire a "change" event at most every 100 milliseconds, and you can use editor.checkDirty() to verify if it has really changed (that call might be a little expensive if you are working with big documents, so it's better to avoid calling it too often by using something like the minimum 100 miliseconds that I've added)

Extra checks

To trap every change (and ASAP to avoid delays updating any UI that it's interested in this event I added also a listener for the afterCommandExec (I don't remember now which situation made me add it and I didn't put any comment explaining it :-(  )

        editor.on( 'afterCommandExec', function( event )
        {
            if ( event.data.command.canUndo !== false )
                somethingChanged();
        } );

and also a listener for the keyboard (don't know right now why I didn't listen for the editor.on('key') event; maybe I forgot about it) and new code to handle drag&drop (I've proposed to enhance the Undo system that way in ticket 7422 with some improved code)

        editor.on( 'contentDom', function()
             {
                 editor.document.on( 'keydown', function( event )
                     {
                         // Do not capture CTRL hotkeys.
                         if ( !event.data.$.ctrlKey && !event.data.$.metaKey )
                             somethingChanged();
                     });

                     // Firefox OK
                 editor.document.on( 'drop', function()
                     {
                         somethingChanged();
                     });
                     // IE OK
                 editor.document.getBody().on( 'drop', function()
                     {
                         somethingChanged();
                     });
             });

Ready to use plugin

Here you can download a zip with the full plugin and install instructions onChange event for CKEditor.
Obviously it can be improved, but the important part was to get something working good enough not to win a code contest about the best and most beautiful code.

Note: If you wanna link the plugin from any other site, please link this post so people can get the new versions when they are released instead of linking directly to the zip that will be outdated.

Edit: version 1.1 3rd September 2011

I've fixed an issue with the 'afterUndo' and 'afterRedo' events: they're fired on their respective commands, not on the editor itself; now the Undo and Redo buttons should work correctly. I can't understand how I missed that the first time.

Following the suggestion in the comments, I've added detection for changes in source mode, by keyboard, drag and drop and also on "input" if supported.

Edit: version 1.2 18th September 2011

The new CKEditor 3.6.2 fired the 'saveSnapshot' event too many times, just changing the focus might fire it and generate bogus change events when nothing has changed. Filtered those extra events.

The keyboard listener has been adjusted to ignore movement and other special keyboard events.

Edit: version 1.3 22th December 2011

Avoid firing the event after the editor has been destroyed.

Edit:

I've published a demo showing an usage example.

Edit: version 1.4 7th September 2012

Don't fire events if the editor is readonly, thanks to Ulrich Gabor.
Included code to use Mutation Observers (I'll try to explain it when I have some time).

Edit: version 1.5 20th October 2012

Detect Cut and Paste for IE in source mode thanks to Jacki.

Edit: version 1.6 18th November 2012

Detect multibyte characters thanks to Wouter.

Edit: version 1.7 6th December 2012

Compatibility with Source mode in CKEditor 4.

Note: 15th December 2012

Although the current version doesn't work correctly with CKEditor 4, I don't plan any future update.

Edit: version 1.8 8th June 2013

Use setInterval fix by Roman Minkin.


Notes to self about the Code highlighter plugin used in WriteArea:

  • It doesn't remember the last used language reverting always to Java
  • It doesn't prefill the content with the currently selected text

2011/02/06

Creating extensions for each browser

These last days I've tried to create a similar extension for each browser, and this is a little recap of the first differences among them. A page with a full list of differences can be found in the State of the Add-on Developer Union

Firefox

In Firefox there are two options:

  1. Create the extension using the "classic" way that goes back to the very beginning and provides full access to anything in Firefox, you can customize it in any way that you like.
  2. Use the new Add-Ons SDK, only for Firefox 4. These ones doesn't require a restart and it's supposed to be future-proof.

In order to create a classic add-on you can get a skeleton using the Add-on Builder . There are lots of info about how to create these extensions and the API that they can use, and to start creating an Add-on the first step is this page to setup the environment. All you need is a text editor, some patience and be careful following the instructions. You can then configure Firefox to load the extension from the disk but when you make changes to the code you'll have to use an extension to force a reload of all the Firefox code or directly restart it; not nice.

To get started building add-ons with the new SDK, check the tutorial.
First problem: You are required to have Python installed.
What?
I'm so tired of projects that say: you have to install this or that or all of these projects just to get started.
What's so special about Python and the SDK environment that can't be done inside Firefox?
Why should I have to keep the list of instructions instead of being able to click on some buttons "Add extension", "Run tests", "Install", "Reload", etc...
Big boo here.
Maybe they want us to use wget instead of Firefox if they think that command line is so nice.

Anyway, I gave it a go in the Mac (I won't bother trying to install python in windows, it has already too many SDKs there for this and that), and so I followed the basic example, while trying at the same time to adjust it to my goal, I add the files, and when I do the "cfx run" then I get a cryptic error "raise ValueError('invalid resource hostname: %s' % name)". WTF? check again that I haven't done anything too weird. Nops. Then put back exactly the sample code. Nops. Search for the message. Bingo!, although there's no warning about this in the tutorial, you CAN'T use uppercase letters in the folder name. Hello Mozilla, it's 2011, I thought that the problems with uppercase and lowercase were gone long ago since MS-DOS. Why aren't your wonderful Python scripts able to deal with them?
Another big fail.

As a summary: I got a bad taste of the Add-ons SDK. When they put forward something that isn't oriented to Python lovers I might test it again (please note that I haven't even tested the API, just the environment makes me go back to keep using the classic method)

Chrome

It seems that there's a lot of work going on here in order to provide a very complete API for the extensions as well as good documentation and lots of examples. You can see a very basic one here and everything is quite easy to follow. Given the fast path that it's set on the release of new Chrome versions we can expect that this trend will continue and that they will add missing features to make some tasks even easier.

The only thing that you need is a text editor and Chrome, and by following the instructions you can get it working. It's not so powerful as the classic extensions in Firefox, but it's really easy to start creating an extension and there are lots of examples to check how they work.

Safari

It seems again that there's plenty of documentation at a central place, but just in the first page there's something strange:

Important: To develop extensions for Safari, you need to sign up for the Safari developer program online, at http://developer.apple.com. You need a signed certificate before your extension can be installed.

Uh?
So to create an sample extension in my own computer I need a certificate?

Ok, this shows again that Apple is a control freak. Why do I have to register to get an Apple ID and then get enrolled into a "Safari developer" program so that I can finally request a signing certificate, just to create a test extension? I can understand that in order to deploy it I might need to sign it, but I really should be able to create an extension for myself without the need to sign two looong agreements with Apple (I'm not sure if there was a paragraph about my first newborn there)

Anyway I go ahead and get a certificate in the Mac, and then it seems to work, but I would like to keep the development environment in Windows, so I try to install the downloaded *.cer there but anyway Safari keeps saying that there's no signing certificate installed. After a little while and some digging I realize that I must export the private signing key from the Mac KeyChain to Windows and once I installed it there Safari started working.

In some regards this might be the simpler interface of all the browsers in order to create an extension as you get a dialog to setup the basic configuration of the extension instead of editing them in a text file. The way that the code is setup is similar to Chrome (and Opera): background pages, injected scripts, so porting from Chrome wasn't a hard task.

As it happens with almost everything Apple does, if you are satisfied with what they offer, they try to make it quite easy, but if you want something extra then it's a no go.

Opera

I started checking the Opera API with the very first builds where they started adding support for extensions. In those days the API wasn't complete, there were a bunch of things that didn't work at all, so due to my hurry to test it I became a little frustrated because there were so many things missing, there was almost no documentation at the moment so it required a lot of effort to try to make something work because the examples were quite basic.

Now they have improved everything a lot, the behavior is similar to Chrome and Safari, but this is still a fresh SDK, so there are still missing features available in other browsers. They have written now lots of documentation and I guess that very shortly it should be quite easy to port an extension between Opera, Chrome and Safari due to the convergence of APIs that the developers find useful.

For the moment Opera it's lacking an API call similar to the ones that I've used for the other browsers so I will put the extension for browser at rest waiting for them to include them instead of struggle again and get tired of finding that it's not possible in any way.

2011/02/03

Mobile test

A quick test of the new blogger application for android

Seems to support only plain text and pictures. Doesn't list existing posts or labels

2011/02/01

WriteArea 1.0.1 Beta 1

Today I've uploaded a beta version of WriteArea to AMO, as I said, it has been updated to CKEditor 3.5.1 but besides that it includes (finally) a feature that it's the way that most of us expected the editor to behave: in-page editing.

This means that the editor is integrated into the page instead of a bottom pane or popup dialog. This feature is still experimental and there might be some unexpected problems, so please be careful (by saving drafts or copy&paste of the contents) before submitting the form.

This feature might have some improvements before the final release, but you can already start testing it

Some drawbacks (at least for the moment):

  • It's not possible to revert the action, once the editor is created it only goes away when the page reloads (might not be a big problem)
  • The clipboard operations are again restricted by default.
  • The Open/Save draft features are no longer available. Maybe I'll adapt them to use HTML5 storage instead of saving to file.

Benefits:

  • It's just easier to use and understand
  • There can be multiple editors in the same page
  • A button can be added so all the textareas are converted without using the context menu

Please, test it and tell me if you notice some problem or if you think that this is really the way to go and the other options should go away.