From 0cf46196829bfd36e702b676c3e1b8324add3baa Mon Sep 17 00:00:00 2001
From: FHenry <florian.henry.mail@gmail.com>
Date: Thu, 1 Mar 2012 14:51:07 +0100
Subject: [PATCH] Emailing campaign- unsubcribe and use of md5 tag

---
 htdocs/comm/mailing/cibles.php                |  1 +
 htdocs/comm/mailing/fiche.php                 | 12 ++-
 .../modules/mailings/modules_mailings.php     | 12 ++-
 htdocs/langs/en_US/mails.lang                 |  7 +-
 htdocs/langs/es_ES/mails.lang                 |  7 +-
 htdocs/langs/fr_FR/mails.lang                 |  7 +-
 htdocs/public/emailing/mailing-read.php       | 25 +++--
 htdocs/public/emailing/mailing-usubscribe.php | 94 +++++++++++++++++++
 scripts/emailings/mailing-send.php            |  5 +-
 9 files changed, 151 insertions(+), 19 deletions(-)
 create mode 100644 htdocs/public/emailing/mailing-usubscribe.php

diff --git a/htdocs/comm/mailing/cibles.php b/htdocs/comm/mailing/cibles.php
index 01cd0bd4347..14b55e80b75 100644
--- a/htdocs/comm/mailing/cibles.php
+++ b/htdocs/comm/mailing/cibles.php
@@ -516,6 +516,7 @@ if ($mil->fetch($id) >= 0)
 					if ($obj->statut==-1) print $langs->trans("MailingStatusError").' '.img_error();
 					if ($obj->statut==1) print $langs->trans("MailingStatusSent").' '.img_picto($langs->trans("MailingStatusSent"),'statut6');
 					if ($obj->statut==2) print $langs->trans("MailingStatusRead").' '.img_picto($langs->trans("MailingStatusRead"),'statut6');
+					if ($obj->statut==3) print $langs->trans("MailingStatusNotContact").' '.img_picto($langs->trans("MailingStatusNotContact"),'statut8');
 					print '</td>';
 				}
 				print '</tr>';
diff --git a/htdocs/comm/mailing/fiche.php b/htdocs/comm/mailing/fiche.php
index 7abf5287ef6..6cf95d57994 100644
--- a/htdocs/comm/mailing/fiche.php
+++ b/htdocs/comm/mailing/fiche.php
@@ -40,7 +40,8 @@ $message = '';
 $substitutionarray=array(
 '__ID__' => 'IdRecord',
 '__EMAIL__' => 'EMail',
-'__CHECK_READ__' => 'CheckMailIsRead',
+'__CHECK_READ__' => 'CheckMail',
+'__UNSUSCRIBE__' => 'Unsuscribe',
 '__LASTNAME__' => 'Lastname',
 '__FIRSTNAME__' => 'Firstname',
 '__OTHER1__' => 'Other1',
@@ -52,7 +53,8 @@ $substitutionarray=array(
 $substitutionarrayfortest=array(
 '__ID__' => 'TESTIdRecord',
 '__EMAIL__' => 'TESTEMail',
-'__CHECK_READ__' => 'TESTCheckMailIsRead',
+'__CHECK_READ__' => 'TESTCheckMail',
+'__UNSUSCRIBE__' => 'TESTUnsuscribe',
 '__LASTNAME__' => 'TESTLastname',
 '__FIRSTNAME__' => 'TESTFirstname',
 '__OTHER1__' => 'TESTOther1',
@@ -135,7 +137,7 @@ if ($_REQUEST["action"] == 'sendallconfirmed' && $_REQUEST['confirm'] == 'yes')
 
 		// On choisit les mails non deja envoyes pour ce mailing (statut=0)
 		// ou envoyes en erreur (statut=-1)
-		$sql = "SELECT mc.rowid, mc.nom, mc.prenom, mc.email, mc.other, mc.source_url, mc.source_id, mc.source_type";
+		$sql = "SELECT mc.rowid, mc.nom, mc.prenom, mc.email, mc.other, mc.source_url, mc.source_id, mc.source_type, mc.tag";
 		$sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc";
 		$sql .= " WHERE mc.statut < 1 AND mc.fk_mailing = ".$id;
 
@@ -180,7 +182,8 @@ if ($_REQUEST["action"] == 'sendallconfirmed' && $_REQUEST['confirm'] == 'yes')
 					$substitutionarray=array(
 						'__ID__' => $obj->source_id,
 						'__EMAIL__' => $obj->email,
-						'__CHECK_READ__' => '<IMG SRC="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?mail_cbl_id='.$obj->rowid.'&mail='.$obj->email.'" style="width:0px;height:0px" border="0"/>',
+						'__CHECK_READ__' => '<img src="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?tag='.$obj->tag.'" style="width:0px;height:0px" border="0"/>',
+						'__UNSUSCRIBE__' => '<a href="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-usubscribe.php?tag='.$obj->tag.'&unsuscrib=1" target="_blank"/>'.$langs->trans("MailUnsubcribe").'</a>',
 						'__LASTNAME__' => $obj->nom,
 						'__FIRSTNAME__' => $obj->prenom,
 						'__OTHER1__' => $other1,
@@ -1030,6 +1033,7 @@ else
 			print '__ID__ = '.$langs->trans("IdRecord").'<br>';
 			print '__EMAIL__ = '.$langs->trans("EMail").'<br>';
 			print '__CHECK_READ__ = '.$langs->trans("CheckRead").'<br>';
+			print '__UNSUSCRIBE__ = '.$langs->trans("MailUnsubcribe").'<br>';
 			print '__LASTNAME__ = '.$langs->trans("Lastname").'<br>';
 			print '__FIRSTNAME__ = '.$langs->trans("Firstname").'<br>';
 			print '__OTHER1__ = '.$langs->trans("Other").'1<br>';
diff --git a/htdocs/core/modules/mailings/modules_mailings.php b/htdocs/core/modules/mailings/modules_mailings.php
index 1f468399cf5..bc5939676a7 100644
--- a/htdocs/core/modules/mailings/modules_mailings.php
+++ b/htdocs/core/modules/mailings/modules_mailings.php
@@ -153,7 +153,7 @@ class MailingTargets    // This can't be abstract as it is used for some method
             $sql = "INSERT INTO ".MAIN_DB_PREFIX."mailing_cibles";
             $sql .= " (fk_mailing,";
             $sql .= " fk_contact,";
-            $sql .= " nom, prenom, email, other, source_url, source_id, source_type)";
+            $sql .= " nom, prenom, email, other, source_url, source_id, tag, source_type)";
             $sql .= " VALUES (".$mailing_id.",";
             $sql .= (empty($cibles[$i]['fk_contact']) ? '0' : "'".$cibles[$i]['fk_contact']."'") .",";
             $sql .= "'".$this->db->escape($cibles[$i]['name'])."',";
@@ -162,6 +162,7 @@ class MailingTargets    // This can't be abstract as it is used for some method
             $sql .= "'".$this->db->escape($cibles[$i]['other'])."',";
             $sql .= "'".$this->db->escape($cibles[$i]['source_url'])."',";
             $sql .= "'".$this->db->escape($cibles[$i]['source_id'])."',";
+            $sql .= "'".$this->db->escape(md5($cibles[$i]['email'].';'.$cibles[$i]['name'].';'.$mailing_id))."',";
             $sql .= "'".$this->db->escape($cibles[$i]['source_type'])."')";
             $result=$this->db->query($sql);
             if ($result)
@@ -183,6 +184,15 @@ class MailingTargets    // This can't be abstract as it is used for some method
 
         dol_syslog(get_class($this)."::add_to_target: mailing ".$j." targets added");
 
+		//Update the status to show poelple that don't want to be contacted anymore'
+        $sql = "UPDATE ".MAIN_DB_PREFIX."mailing_cibles";
+        $sql .= " SET statut=3";
+        $sql .= " WHERE fk_mailing=".$mailing_id." and email in (SELECT email FROM ".MAIN_DB_PREFIX."societe where fk_stcomm=-1)";
+        $result=$this->db->query($sql);
+
+        dol_syslog("MailingTargets::add_to_target: mailing update status to display people that do not want to be contacted sql:".$sql);
+
+
         $this->update_nb($mailing_id);
 
         $this->db->commit();
diff --git a/htdocs/langs/en_US/mails.lang b/htdocs/langs/en_US/mails.lang
index 04eddbf9791..9ada97fc97b 100644
--- a/htdocs/langs/en_US/mails.lang
+++ b/htdocs/langs/en_US/mails.lang
@@ -39,12 +39,14 @@ MailingStatusDraft=Draft
 MailingStatusValidated=Validated
 MailingStatusApproved=Approved
 MailingStatusSent=Sent
-MailingStatusRead=Read
 MailingStatusSentPartialy=Sent partialy
 MailingStatusSentCompletely=Sent completely
 MailingStatusError=Error
 MailingStatusNotSent=Not sent
 MailSuccessfulySent=Email successfully sent (from %s to %s)
+MailUnsubcribe=Unsubscribe
+Unsuscribe=Unsubscribe
+MailingStatusNotContact=Don't contact anymore
 ErrorMailRecipientIsEmpty=Email recipient is empty
 WarningNoEMailsAdded=No new Email to add to recipient's list.
 ConfirmValidMailing=Are you sure you want to validate this emailing ?
@@ -70,6 +72,9 @@ CloneReceivers=Cloner recipients
 DateLastSend=Date of last sending
 DateSending=Date sending
 SentTo=Sent to <b>%s</b>
+MailingStatusRead=Read
+CheckRead=Read Receipt
+YourMailUnsubcribeOK=The email <b>%s</b>  is correctly unsubcribe from mailing list
 
 # Libelle des modules de liste de destinataires mailing
 MailingModuleDescContactCompanies=Contacts of all third parties (customer, prospect, supplier, ...)
diff --git a/htdocs/langs/es_ES/mails.lang b/htdocs/langs/es_ES/mails.lang
index 3957b886cae..c068a7d57d4 100644
--- a/htdocs/langs/es_ES/mails.lang
+++ b/htdocs/langs/es_ES/mails.lang
@@ -39,12 +39,13 @@ MailingStatusDraft=Borrador
 MailingStatusValidated=Validado
 MailingStatusApproved=Aprovado
 MailingStatusSent=Enviado
-MailingStatusRead=Leido
 MailingStatusSentPartialy=Enviado parcialmente
 MailingStatusSentCompletely=Enviado completamente
 MailingStatusError=Error
 MailingStatusNotSent=No enviado
 MailSuccessfulySent=E-Mail enviado correctamente (de %s a %s)
+MailUnsubcribe=Desuscribe
+Unsuscribe=Desuscribe
 ErrorMailRecipientIsEmpty=La dirección del destinatario está vacía
 WarningNoEMailsAdded=Ningún nuevo E-Mailing a añadir a la lista destinatarios.
 ConfirmValidMailing=¿Confirma la validación del E-Mailing?
@@ -70,6 +71,10 @@ CloneReceivers=Clonar destinatarios
 DateLastSend=Fecha último envío
 DateSending=Fecha envío
 SentTo=Enviado a <b>%s</b>
+MailingStatusRead=Leido
+CheckRead=Confirmación de lectura
+YourMailUnsubcribeOK=El correo electrónico <b>%s</b> es correcta desuscribe.
+
 # Libelle des modules de liste de destinataires mailing=
 MailingModuleDescContactCompanies=Contactos de terceros (clientes potenciales, clientes, proveedores...)
 MailingModuleDescDolibarrUsers=Usuarios de Dolibarr
diff --git a/htdocs/langs/fr_FR/mails.lang b/htdocs/langs/fr_FR/mails.lang
index 591000e00d8..c80a79615aa 100644
--- a/htdocs/langs/fr_FR/mails.lang
+++ b/htdocs/langs/fr_FR/mails.lang
@@ -39,12 +39,14 @@ MailingStatusDraft=Brouillon
 MailingStatusValidated=Validé
 MailingStatusApproved=Approuvé
 MailingStatusSent=Envoyé
-MailingStatusRead=Lu
 MailingStatusSentPartialy=Envoyé partiellement
 MailingStatusSentCompletely=Envoyé complètement
 MailingStatusError=Erreur
 MailingStatusNotSent=Non envoyé
 MailSuccessfulySent=Mail correctement envoyé (de %s à %s)
+MailUnsubcribe=Desinscription
+Unsuscribe=Desinscription
+MailingStatusNotContact=Ne plus contacter
 ErrorMailRecipientIsEmpty=L'adresse du destinataire est vide
 WarningNoEMailsAdded=Aucun nouvel e-mail à ajouter à la liste des destinataires.
 ConfirmValidMailing=Confirmez-vous la validation du mailing ?
@@ -70,6 +72,9 @@ CloneReceivers=Cloner destinataires
 DateLastSend=Date du dernier envoi
 DateSending=Date envoi
 SentTo=Envoyés à <b>%s</b>
+MailingStatusRead=Lu
+CheckRead=Accusé de lecture
+YourMailUnsubcribeOK=L'adresse e-mail <b>%s</b> est bien désincrite de la liste.
 
 # Libelle des modules de liste de destinataires mailing
 MailingModuleDescContactCompanies=Contacts de tiers (prospects, clients, fournisseurs...)
diff --git a/htdocs/public/emailing/mailing-read.php b/htdocs/public/emailing/mailing-read.php
index e1271a71f41..9b5721b70da 100644
--- a/htdocs/public/emailing/mailing-read.php
+++ b/htdocs/public/emailing/mailing-read.php
@@ -31,16 +31,23 @@ define("NOCSRFCHECK",1);	// We accept to go on this page from external web site.
 
 require("../../main.inc.php");
 
-$id=GETPOST('mail_cbl_id');
-$mail_reader=GETPOST('mail');
+$id=GETPOST('tag');
+
+
+if ($id!='')
+{
+	$statut='2';
+	$sql = "UPDATE ".MAIN_DB_PREFIX."mailing_cibles SET statut=".$statut." WHERE tag='".$id."'";
+	dol_syslog("public/emailing/mailing-read.php : Mail read : ".$sql, LOG_DEBUG);
+	
+	$resql=$db->query($sql);
+	
+	$sql = "UPDATE ".MAIN_DB_PREFIX."societe SET fk_stcomm=2 WHERE rowid IN (SELECT source_id FROM ".MAIN_DB_PREFIX."mailing_cibles WHERE tag='".$id."')";
+	dol_syslog("public/emailing/mailing-read.php : Mail read : ".$sql, LOG_DEBUG);
+	
+	$resql=$db->query($sql);
+}
 
 
-$statut='2';
-
-$sql = "UPDATE ".MAIN_DB_PREFIX."mailing_cibles SET statut=".$statut." WHERE rowid=".$id." AND email='".$mail_reader."'";
-dol_syslog("public/emailing/mailing-read.php : Mail read : ".$sql, LOG_DEBUG);
-
-$resql=$db->query($sql);
-
 $db->close();
 ?>
diff --git a/htdocs/public/emailing/mailing-usubscribe.php b/htdocs/public/emailing/mailing-usubscribe.php
new file mode 100644
index 00000000000..a46946b9661
--- /dev/null
+++ b/htdocs/public/emailing/mailing-usubscribe.php
@@ -0,0 +1,94 @@
+<?php
+/*
+ * Copyright (C) 2004      Rodolphe Quiedeville <rodolphe@quiedeville.org>
+ * Copyright (C) 2005-2011 Laurent Destailleur  <eldy@users.sourceforge.net>
+ * Copyright (C) 2012	   Florian Henry  <florian.henry@open-concept.pro>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+
+/**
+ *      \file       scripts/emailings/mailing-read.php
+ *      \ingroup    mailing
+ *      \brief      Script use to update unsubcribe contact to prospect mailing list
+ */
+ 
+define("NOLOGIN",1);		// This means this output page does not require to be logged.
+define("NOCSRFCHECK",1);	// We accept to go on this page from external web site.
+
+require("../../main.inc.php");
+require_once(DOL_DOCUMENT_ROOT."/lib/company.lib.php");
+
+global $user, $conf, $langs;
+
+$langs->load("main");
+$langs->load("mails");
+
+$id=GETPOST('tag');
+$unsuscrib=GETPOST('unsuscrib');
+
+
+if (($id!='') && ($unsuscrib=='1'))
+{
+	//Udate status of mail in Destinaries maling list
+	$statut='3';
+	$sql = "UPDATE ".MAIN_DB_PREFIX."mailing_cibles SET statut=".$statut." WHERE tag='".$id."'";
+	dol_syslog("public/emailing/mailing-read.php : Mail unsubcribe : ".$sql, LOG_DEBUG);
+	
+	$resql=$db->query($sql);
+	
+	//Update status communication of prospect
+	$sql = "UPDATE ".MAIN_DB_PREFIX."societe SET fk_stcomm=-1 WHERE rowid IN (SELECT source_id FROM ".MAIN_DB_PREFIX."mailing_cibles WHERE tag='".$id."' AND source_type='thirdparty')";
+	dol_syslog("public/emailing/mailing-read.php : Mail unsubcribe : ".$sql, LOG_DEBUG);
+	
+	$resql=$db->query($sql);
+
+	$sql = "SELECT mc.email";
+	$sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc";
+	$sql .= " WHERE mc.tag='".$id."'";
+
+	$resql=$db->query($sql);
+	
+	$obj = $db->fetch_object($resql);
+	
+	header("Content-type: text/html; charset=".$conf->file->character_set_client);
+
+	print '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">';
+	print "\n";
+	print "<html>\n";
+	print "<head>\n";
+	print '<meta name="robots" content="noindex,nofollow">'."\n";
+	print '<meta name="keywords" content="dolibarr,mailing">'."\n";
+	print '<meta name="description" content="Welcome on Dolibarr Mailing unsubcribe">'."\n";
+	print "<title>".$langs->trans("MailUnsubcribe")."</title>\n";
+	print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.$conf->css.'?lang='.$langs->defaultlang.'">'."\n";
+	print '<style type="text/css">';
+	print '.CTableRow1      { margin: 1px; padding: 3px; font: 12px verdana,arial; background: #e6E6eE; color: #000000; -moz-border-radius-topleft:6px; -moz-border-radius-topright:6px; -moz-border-radius-bottomleft:6px; -moz-border-radius-bottomright:6px;}';
+	print '.CTableRow2      { margin: 1px; padding: 3px; font: 12px verdana,arial; background: #FFFFFF; color: #000000; -moz-border-radius-topleft:6px; -moz-border-radius-topright:6px; -moz-border-radius-bottomleft:6px; -moz-border-radius-bottomright:6px;}';
+	print '</style>';
+
+	print "</head>\n";
+	print '<body style="margin: 20px;">'."\n";
+	print '<table><tr><td style="text_align:center;">';
+	print $langs->trans("YourMailUnsubcribeOK",$obj->email)."<br>\n";
+	print '</td></tr></table>';
+	print "</body>\n";
+	print "</html>\n";
+	
+
+}
+
+$db->close();
+?>
diff --git a/scripts/emailings/mailing-send.php b/scripts/emailings/mailing-send.php
index 13d28f95eda..f3923ed0567 100644
--- a/scripts/emailings/mailing-send.php
+++ b/scripts/emailings/mailing-send.php
@@ -93,7 +93,7 @@ $nbok=0; $nbko=0;
 
 // On choisit les mails non deja envoyes pour ce mailing (statut=0)
 // ou envoyes en erreur (statut=-1)
-$sql = "SELECT mc.rowid, mc.nom as lastname, mc.prenom as firstname, mc.email, mc.other, mc.source_url, mc.source_id, mc.source_type";
+$sql = "SELECT mc.rowid, mc.nom as lastname, mc.prenom as firstname, mc.email, mc.other, mc.source_url, mc.source_id, mc.source_type, mc.tag";
 $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc";
 $sql .= " WHERE mc.statut < 1 AND mc.fk_mailing = ".$id;
 
@@ -135,7 +135,8 @@ if ($resql)
 			$substitutionarray=array(
 				'__ID__' => $obj->source_id,
 				'__EMAIL__' => $obj->email,
-				'__CHECK_READ__' => '<IMG SRC="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?mail_cbl_id='.$obj->rowid.'&mail='.$obj->email.'" style="width:0px;height:0px" border="0"/>',
+				'__CHECK_READ__' => '<img src="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?tag='.$obj->tag.'" style="width:0px;height:0px" border="0"/>',
+				'__UNSUSCRIBE__' => '<a href="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-usubscribe.php?tag='.$obj->tag.'&unsuscrib=1" target="_blank"/>'.$langs->trans("MailUnsubcribe").'</a>',
 				'__LASTNAME__' => $obj->lastname,
 				'__FIRSTNAME__' => $obj->firstname,
 				'__OTHER1__' => $other1,
-- 
GitLab