Diferencia entre revisiones de «Procesando el correo»

De MoodleDocs
Línea 70: Línea 70:
     noreply: |/var/www/moodle/admin/process_email.php
     noreply: |/var/www/moodle/admin/process_email.php


If you are using virtualdomains, consult your server administrator for the correct configuration. It probably involves editing transports and mapping your address to a "pipe" transport.
Si estás utilizando dominios virtuales, consulta al administrador de tu sistema para la configuración correcta. Probablemente incluirá editar transportes y mapear tu dirección a una "pila(''"pipe"'')de transporte.


More documentation about Exim can be found here. You may have to tell Exim not to lowercase the local-part.
Puedes encontrar aquí mas documentación sobre Exim. Puede que tengas que indicar a Exim que no ponga en minúsculas la parte local(''local-part'').


== Developer info ==
== Developer info ==

Revisión del 16:07 24 mar 2006

Nota: Pendiente de Traducir. ¡Anímese a traducir esta página!.     ( y otras páginas pendientes)

Características

Ahora moodle hace mejor uso del protocolo SMTP y correo en general. La mayoría de las mejoras provienen de utilizar una técnica conocida como Variable Envelope Return Path(Variable envolvente de la ruta de retorno) (VERP).

  • Funciona en los más modernos MTAs (al menos en los sistemas Unix).
  • Se aseguran todos los procesos de rebotes y réplicas utilizando HMAC-MD5-8.
  • Los rebotes(bounces) se manejan correctamente e incrementa el almacenamiento de "correo erróneo"("bad email") para el usuario.
  • La dirección noreply@host está ahora en el campo Reply-to(Responder), evitando la contaminación accidental de los libros de direcciones( agendas) de los usuarios.
  • noreply@host tiene un autorresponder
  • Facilita a los módulos el envío de correo con la opción VERP reply-to(responder) marcada.
  • Manejadores que reciben respuestas VERP: Validan la firma de HMAC-MD5-8 y envían los datos requeridos codificados al módulo indicado

Configuración Moodle

Edita config.php para habilitar manejo de rebotes(bounce), y configura las especificaciones de Moodle para que coincidan con tu configuración MTA. Aquí está cómo: Quita los comentarios a estas líneas en el archivo config.php (si no puedes encontrarlas, cópialas del archivo config-dist.php):

 // once handlebounces is true, we will be using VERP for the return address of every sent
email(con handlebounces en verdadero. utilizaremos VERP para coger la dirección origen de
cada email enviado
) $CFG->handlebounces = true; // minimum bounces allowed per user(rebotes mínimos por usuario) $CFG->minbounces = 10; // ratio of bad emails to sent emails(estadística de correo erróneo en correo enviado) // if we get more than 20% bounces ( si es mayor del 20% los rebotes) // for a given user, his/her email is marked bad(de un usuario concreto, su email se marca
como erróneo
) $CFG->bounceratio = .20;

Edita la línea $CFG->maildomain y una de las líneas $CFG->mailprefix (la que coincida con tu MTA).

Asegúrate de que tu servidor tenga un intérprete de línea de comando PHP, y que es posible conectar con mysql (o postgres). Si eres capaz de ejecutar cron.php desde la línea de comandos o desde crontab, significa que PHP funciona.

Edita el script process_email.php para que contenga la localización de tu binario PHP. Será de la forma /usr/bin/php.

Asegúrate que process_email.php sea ejecutable utilizando la instrucción "chmod ugo+rx process_email.php".

Configuración bajo Postfix

Añade una línea a tu archivo alias. La línea contendrá un prefijo de 3 letras, un signo "+" y la ruta al script. Por ejemplo, si el prefijo es mdl y moodle instalado bajo /var/www/moodle tendríamos en el alias:

   mdl:     |/var/www/moodle/admin/process_email.php
   noreply: |/var/www/moodle/admin/process_email.php

Si estás utilizando dominios virtuales, consulta al administrador de tu sistema para la configuración correcta. Probablemente incluirá editar transportes y mapear tu dirección a una "pila("pipe")de transporte.

Configuración bajo Qmail

Dependiendo de su configuración, su alias se controlará por una o más de

  • /etc/aliases
  • /var/qmail/alias/.qmail-PREFIX

Si edita /etc/aliases añadiendo una línea como (para un prefijo 'mdl'):

   mdl:     |/var/www/moodle/admin/process_email.php
   noreply: |/var/www/moodle/admin/process_email.php

Si crea /var/qmail/alias/.qmail-PREFIX, simplemente realice

 echo "|/var/www/moodle/admin/process_email.php" > /var/qmail/alias/.qmail-mdl
 echo "|/var/www/moodle/admin/process_email.php" > /var/qmail/alias/.qmail-noreply

A este prefijo de tres letras, añadiremos un signo '-' cuando enviemos y recibamos mensajes. Para más información, comprueba el manejo de dot-qmail.

Configuración bajo Exim

Abre /etc/exim/exim.conf y añade a usuarios de confianza(trusted_users) el usuario Apache y cron.php se ejecutará así (generalmente "www-data" o "nobody").

Añade una ínea a tu archivo alias. La línea contendrá un prefijo de 3 letras, más un signo "+", y la ruta del script. Por ejemplo, para un prefijo de mdl tendremos en el alias:

   mdl:     |/var/www/moodle/admin/process_email.php
   noreply: |/var/www/moodle/admin/process_email.php

Si estás utilizando dominios virtuales, consulta al administrador de tu sistema para la configuración correcta. Probablemente incluirá editar transportes y mapear tu dirección a una "pila("pipe")de transporte.

Puedes encontrar aquí mas documentación sobre Exim. Puede que tengas que indicar a Exim que no ponga en minúsculas la parte local(local-part).

Developer info

Changed functions:

  • email_to_user() will set the envelope sender to a special bounce processing address (based on $CFG settings)
  • email_to_user() will accept (and set) a reply-to header, to be generated by the module calling the function.
  • associated string changes/additions

New functions:

  • generate_email_processing_address() - ALWAYS use this to generate the reply-to header. reply-to header will look like this: (LIMIT: 64 chars total) prefix - EXACTLY four chars encodeded, packed, moduleid (0 for core) (2 chars) up to 42 chars for the modules to put anything they want it (can contain userid (or, eg for forum, postids to reply to), or anything really. 42 chars is ABSOLUTE LIMIT) 16 char hash (half an md5) of the first part of the address, together with a site "secret"
  • moodle_process_email() - any non-module email processing goes here (currently used for processing bounces)

New files:

admin/process_email.php

This script needs to be called from your MTA for anything starting with the 3 char prefix described above (and optionally, the noreply address).

How does it work? It will break down and unencode the email address into moduleid and validate the half md5 hash, and call $modname_process_email (if it exists). Arguments to these functions are: $modargs (any part of the email address that isn't the prefix, modid or the hash) and the contents of the email (read from STDIN).

It doubles up as the noreplyaddress autorresponder if you configure it with that address as well. Replying with a friendly "this is not a real email address" message.

Module Authors

Take a look at new functions moodle_process_email() and generate_email_processing_address() in moodlelib.php for ideas about how to

  • encode and unencode the arguments your module needs to do the processing
  • how to deal with multiple "actions" for any given module.

In a nutshell, users can send emails to Moodle using special dynamic addresses. These emails can trigger a call to a module function in the form of modulename_process_email($str, $bodyofemail). The $str part will be up to 42 characters of data generated by Moodle (presumably by your own module), and the $bodyofemailpart is the contents of the email (got by reading STDIN - usually generated by the users MUA).

The 42 characters come from the "local part" of an email address (the part before the @ sign) which can have up to 64 chars. Out of those 64 chars, Moodle uses 22 characters, leaving you with 42 characters to encode data.

What do we do with the 22 chars? Four go to the prefix, which we need to let the MTA know to pass the message to our script. Two go to identify the module ID so we know which module has generated the message (and so we dispatch the request to that module). The remaining 16 are a signature (HMAC-MD5-8) we use to authenticate the message.

Forty-two characters isn't a lot (although it could be the answer to life, the universe, and everything!) so make sure you use those characters wisely.

The most efficient way to encode database IDs in their full range (so that they can be placed in an email address) we have found is base64_encode(pack('V',2147483647)), which returns "/ / / / f w = =". The two trailing "= =" are redundant and you can remove them (you'll need to reappend them when retrieving your data). Join your parameters as encoded IDs in positional slots for efficiency.

To retrieve your data, use substr() to separate your parameters, and then unpack('V',base64_decode($str)). Note that it'll return a one-element array. Note:

Using 'V' reaches 2147483647, half the range of mySQL's INT. Additionally, 'V' behaves like a signed value, rather than an unsigned, so I suspect there's a bug in PHP's documentation of pack().

With each ID taking 6-chars (8 chars if we find a way to use the full range of 'V'), you have a limited number of parameters. If you need to encode more information, store it in the DB and send emails that point to your stored data. Remember to cleanup this temporary data after a safe period of time.

Note:

Do not try to use variable-width encoding to put IDs, as it'll work in small installations and break in larger ones.

Security issues

Any code in modulename_process_email() _must_ assume it will see repeat replies and handle them gracefully. The definition of 'gracefully' depends on what the code does.

Email servers (MTAs) will sometimes re-transmit a message if they are unsure that the receiving MTA got it -- and sysadmins may sometimes replay a whole email queue if something's gone wrong. In that case, they email body will be identical, the headers slightly different.

In a different case, the user may 'reply' to the message twice. Perhaps in error, perhaps purposefully. What to do depends on the specific scenario.

We /could/ support better protection at the framework level, by keeping track of every reply-to address we send out. We decided against that because (a) the performance impact will be important (b) we want the 1st cut to be lightweight and simple to change in case we need to.

With this the initial implementation, modules should expose functions that handle these "replay" cases correctly. If later we want to expose additional functions, we can add such tracking as an optional thing. It'd be awful to have it across all emails sent from Moodle.