From 0fc1c85b349859739ff557f0cace018bf8da6d7a Mon Sep 17 00:00:00 2001
From: Laurent Destailleur <eldy@destailleur.fr>
Date: Sat, 25 Oct 2014 00:42:52 +0200
Subject: [PATCH] New: Module notification has been enhanced: EMail use now
 language of target contact. Can also define a fixed email for notifications.
 Better error management

---
 ChangeLog                                     |   3 +
 htdocs/admin/notification.php                 |  46 ++-
 htdocs/commande/card.php                      |   2 +-
 htdocs/core/class/notify.class.php            | 352 +++++++++++++-----
 htdocs/core/lib/functions.lib.php             |   2 +
 ..._50_modNotification_Notification.class.php |  62 +--
 htdocs/langs/en_US/admin.lang                 |   7 +-
 htdocs/langs/en_US/other.lang                 |   1 +
 htdocs/societe/notify/card.php                |  35 +-
 9 files changed, 340 insertions(+), 170 deletions(-)

diff --git a/ChangeLog b/ChangeLog
index 350f5ba7b6d..36439c46288 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -5,6 +5,9 @@ English Dolibarr ChangeLog
 
 ***** ChangeLog for 3.7 compared to 3.6.* *****
 For users:
+- New: Module notification has been enhanced:
+       EMail use now language of target contact.
+       Can also define a fixed email for notifications.
 - New: Feature to link manually an order to an invoice does not disappear once
        link has been done.
 - New: Can set a color on user card (visible into agenda view).
diff --git a/htdocs/admin/notification.php b/htdocs/admin/notification.php
index ca68c54c805..14aeba65c29 100644
--- a/htdocs/admin/notification.php
+++ b/htdocs/admin/notification.php
@@ -32,6 +32,7 @@ $langs->load("other");
 $langs->load("orders");
 $langs->load("propal");
 $langs->load("bills");
+$langs->load("errors");
 
 // Security check
 if (!$user->admin)
@@ -39,19 +40,32 @@ if (!$user->admin)
 
 $action = GETPOST("action");
 
+
 /*
  * Actions
  */
 
 if ($action == 'setvalue' && $user->admin)
 {
-	$result=dolibarr_set_const($db, "NOTIFICATION_EMAIL_FROM",$_POST["email_from"],'chaine',0,'',$conf->entity);
-  	if ($result >= 0)
+	$result=dolibarr_set_const($db, "NOTIFICATION_EMAIL_FROM", $_POST["email_from"], 'chaine', 0, '', $conf->entity);
+    if ($result < 0) $error++;
+
+    if (! $error)
+    {
+	    foreach($_POST as $key => $val)
+	    {
+	    	if (! preg_match('/^NOTIFICATION_FIXEDEMAIL_/',$key)) continue;
+	    	//print $key.' - '.$val.'<br>';
+			$result=dolibarr_set_const($db, $key, $val, 'chaine', 0, '', $conf->entity);
+	    }
+    }
+
+  	if (! $error)
     {
         setEventMessage($langs->trans("SetupSaved"));
     }
     else
-    {
+	{
         setEventMessage($langs->trans("Error"),'errors');
     }
 }
@@ -67,7 +81,7 @@ llxHeader();
 $linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php">'.$langs->trans("BackToModuleList").'</a>';
 print_fiche_titre($langs->trans("NotificationSetup"),$linkback,'setup');
 
-print $langs->trans("NotificationsDesc").'<br><br>';	
+print $langs->trans("NotificationsDesc").'<br><br>';
 
 print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">';
 print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
@@ -83,19 +97,13 @@ print "</tr>\n";
 $var=!$var;
 print '<tr '.$bc[$var].'><td>';
 print $langs->trans("NotificationEMailFrom").'</td><td>';
-print '<input size="32" type="text" name="email_from" value="'.$conf->global->NOTIFICATION_EMAIL_FROM.'">';
-if (! empty($conf->global->NOTIFICATION_EMAIL_FROM) && ! isValidEmail($conf->global->NOTIFICATION_EMAIL_FROM)) print ' '.img_warning($langs->trans("BadEMail"));
+print '<input size="32" type="email" name="email_from" value="'.$conf->global->NOTIFICATION_EMAIL_FROM.'">';
+if (! empty($conf->global->NOTIFICATION_EMAIL_FROM) && ! isValidEmail($conf->global->NOTIFICATION_EMAIL_FROM)) print ' '.img_warning($langs->trans("ErrorBadEMail"));
 print '</td></tr>';
 print '</table>';
 
 print '<br>';
 
-print '<center><input type="submit" class="button" value="'.$langs->trans("Modify").'"></center>';
-
-print '</form>';
-print '<br>';
-
-
 print_fiche_titre($langs->trans("ListOfAvailableNotifications"),'','');
 
 print '<table class="noborder" width="100%">';
@@ -103,6 +111,7 @@ print '<tr class="liste_titre">';
 print '<td>'.$langs->trans("Module").'</td>';
 print '<td>'.$langs->trans("Code").'</td>';
 print '<td>'.$langs->trans("Label").'</td>';
+print '<td>'.$langs->trans("FixedEmailTarget").'</td>';
 print "</tr>\n";
 
 // Load array of available notifications
@@ -123,10 +132,21 @@ foreach($listofnotifiedevents as $notifiedevent)
     print '<td>'.$elementLabel.'</td>';
     print '<td>'.$notifiedevent['code'].'</td>';
     print '<td>'.$label.'</td>';
+    $param='NOTIFICATION_FIXEDEMAIL_'.$notifiedevent['code'];
+    print '<td><input type="email" size="32" name="'.$param.'" value="'.dol_escape_htmltag(GETPOST($param)?GETPOST($param,'alpha'):$conf->global->$param).'">';
+	if (! empty($conf->global->$param) && ! isValidEmail($conf->global->$param)) print ' '.img_warning($langs->trans("ErrorBadEMail"));
+    print '</td>';
     print '</tr>';
 }
 print '</table>';
 
-$db->close();
+print '<br>';
+
+print '<center><input type="submit" class="button" value="'.$langs->trans("Save").'"></center>';
+
+print '</form>';
+
 
 llxFooter();
+
+$db->close();
diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php
index 8485ec05f96..82811287604 100644
--- a/htdocs/commande/card.php
+++ b/htdocs/commande/card.php
@@ -1,6 +1,6 @@
 <?php
 /* Copyright (C) 2003-2006	Rodolphe Quiedeville	<rodolphe@quiedeville.org>
- * Copyright (C) 2004-2013	Laurent Destailleur		<eldy@users.sourceforge.net>
+ * Copyright (C) 2004-2014	Laurent Destailleur		<eldy@users.sourceforge.net>
  * Copyright (C) 2005		Marc Barilley / Ocebo	<marc@ocebo.com>
  * Copyright (C) 2005-2013	Regis Houssin			<regis.houssin@capnetworks.com>
  * Copyright (C) 2006		Andre Cianfarani		<acianfa@free.fr>
diff --git a/htdocs/core/class/notify.class.php b/htdocs/core/class/notify.class.php
index 43a504fd04f..b7914be6e77 100644
--- a/htdocs/core/class/notify.class.php
+++ b/htdocs/core/class/notify.class.php
@@ -32,6 +32,7 @@ class Notify
     var $id;
     var $db;
     var $error;
+    var $errors=array();
 
     var $author;
     var $ref;
@@ -84,34 +85,50 @@ class Notify
 	{
 		global $conf;
 
-        $num=-1;
+		$error=0;
+        $num=0;
 
-        $sql = "SELECT n.rowid";
-        $sql.= " FROM ".MAIN_DB_PREFIX."notify_def as n,";
-        $sql.= " ".MAIN_DB_PREFIX."socpeople as c,";
-        $sql.= " ".MAIN_DB_PREFIX."c_action_trigger as a,";
-        $sql.= " ".MAIN_DB_PREFIX."societe as s";
-        $sql.= " WHERE n.fk_contact = c.rowid";
-        $sql.= " AND a.rowid = n.fk_action";
-        $sql.= " AND n.fk_soc = s.rowid";
-        if (is_numeric($action)) $sql.= " AND n.fk_action = ".$action;	// Old usage
-        else $sql.= " AND a.code = '".$action."'";	// New usage
-        $sql.= " AND s.entity IN (".getEntity('societe', 1).")";
-        $sql.= " AND s.rowid = ".$socid;
-
-		dol_syslog("Notify.class::countDefinedNotifications ".$action.", ".$socid."", LOG_DEBUG);
-
-        $resql = $this->db->query($sql);
-        if ($resql)
+        if (! $error)
         {
-            $num = $this->db->num_rows($resql);
-		}
-		else
+	        $sql = "SELECT n.rowid";
+	        $sql.= " FROM ".MAIN_DB_PREFIX."notify_def as n,";
+	        $sql.= " ".MAIN_DB_PREFIX."socpeople as c,";
+	        $sql.= " ".MAIN_DB_PREFIX."c_action_trigger as a,";
+	        $sql.= " ".MAIN_DB_PREFIX."societe as s";
+	        $sql.= " WHERE n.fk_contact = c.rowid";
+	        $sql.= " AND a.rowid = n.fk_action";
+	        $sql.= " AND n.fk_soc = s.rowid";
+	        if (is_numeric($action)) $sql.= " AND n.fk_action = ".$action;	// Old usage
+	        else $sql.= " AND a.code = '".$action."'";	// New usage
+	        $sql.= " AND s.entity IN (".getEntity('societe', 1).")";
+	        $sql.= " AND s.rowid = ".$socid;
+
+			dol_syslog(get_class($this)."::countDefinedNotifications ".$action.", ".$socid."", LOG_DEBUG);
+
+	        $resql = $this->db->query($sql);
+	        if ($resql)
+	        {
+	            $num = $this->db->num_rows($resql);
+			}
+			else
+			{
+				$error++;
+				$this->error=$this->db->error.' sql='.$sql;
+			}
+        }
+
+		if (! $error)
 		{
-			$this->error=$this->db->error.' sql='.$sql;
-			return -1;
+		    // List of notifications enabled for fixed email
+		    foreach($conf->global as $key => $val)
+		    {
+		    	if (! preg_match('/^NOTIFICATION_FIXEDEMAIL_'.$action.'/', $key, $reg)) continue;
+		    	$num++;
+		    }
 		}
 
+		// TODO return array with list of email instead of number, + type of notification (contacts or fixed email)
+		if ($error) return -1;
 		return $num;
 	}
 
@@ -120,22 +137,42 @@ class Notify
      * 	If yes, send mail and save trace into llx_notify.
      *
      * 	@param	string	$action		Code of action in llx_c_action_trigger (new usage) or Id of action in llx_c_action_trigger (old usage)
-     * 	@param	int		$socid		Id of third party
-     * 	@param	string	$texte		Message to send
-     * 	@param	string	$objet_type	Type of object the notification deals on (facture, order, propal, order_supplier...). Just for log in llx_notify.
-     * 	@param	int		$objet_id	Id of object the notification deals on
-     * 	@param	string	$file		Attach a file
+     * 	@param	Object	$object		Object the notification deals on
      *	@return	int					<0 if KO, or number of changes if OK
      */
-    function send($action, $socid, $texte, $objet_type, $objet_id, $file="")
+    function send($action, $object)
     {
         global $conf,$langs,$mysoc,$dolibarr_main_url_root;
 
-        $langs->load("other");
+	    include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+		dol_syslog(get_class($this)."::send action=".$action.", object=".$object->id);
+
+    	$langs->load("other");
+
+		// Define $urlwithroot
+	    $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
+		$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;			// This is to use external domain name found into config file
+		//$urlwithroot=DOL_MAIN_URL_ROOT;						// This is to use same domain name than current
 
-		dol_syslog(get_class($this)."::send action=".$action.", socid=".$socid.", texte=".$texte.", objet_type=".$objet_type.", objet_id=".$objet_id.", file=".$file);
+		// Define some vars
+	    $application = $mysoc->name;
+	    //if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $application = $conf->global->MAIN_APPLICATION_TITLE;
+	    $replyto = $conf->notification->email_from;
+	    $filename = basename($file);
+        $mimefile = dol_mimetype($file);
+		$object_type = '';
+        $link = '';
+		$num = 0;
 
-		$sql = "SELECT s.nom, c.email, c.rowid as cid, c.lastname, c.firstname,";
+		if (! in_array($action, array('BILL_VALIDATE', 'ORDER_VALIDATE', 'PROPAL_VALIDATE', 'FICHINTER_VALIDATE', 'ORDER_SUPPLIER_APPROVE', 'ORDER_SUPPLIER_REFUSE', 'SHIPPING_VALIDATE')))
+		{
+			return 0;
+		}
+
+
+		// Check notification per third party
+		$sql = "SELECT s.nom, c.email, c.rowid as cid, c.lastname, c.firstname, c.default_lang,";
 		$sql.= " a.rowid as adid, a.label, a.code, n.rowid";
         $sql.= " FROM ".MAIN_DB_PREFIX."socpeople as c,";
         $sql.= " ".MAIN_DB_PREFIX."c_action_trigger as a,";
@@ -145,7 +182,7 @@ class Notify
         $sql.= " AND n.fk_soc = s.rowid";
         if (is_numeric($action)) $sql.= " AND n.fk_action = ".$action;	// Old usage
         else $sql.= " AND a.code = '".$action."'";	// New usage
-        $sql .= " AND s.rowid = ".$socid;
+        $sql .= " AND s.rowid = ".$object->socid;
 
         $result = $this->db->query($sql);
         if ($result)
@@ -155,7 +192,7 @@ class Notify
             if ($num > 0)
             {
 	            $i = 0;
-	            while ($i < $num)	// For each notification couple defined (third party/actioncode)
+	            while ($i < $num && ! $error)	// For each notification couple defined (third party/actioncode)
 	            {
 	                $obj = $this->db->fetch_object($result);
 
@@ -164,48 +201,80 @@ class Notify
 
 	                if (dol_strlen($obj->email))
 	                {
-	                	include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
-	                	$application=($conf->global->MAIN_APPLICATION_TITLE?$conf->global->MAIN_APPLICATION_TITLE:'Dolibarr ERP/CRM');
-
-	                	$subject = '['.$application.'] '.$langs->transnoentitiesnoconv("DolibarrNotification");
-
-	                	$message = $langs->transnoentities("YouReceiveMailBecauseOfNotification",$application,$mysoc->name)."\n";
-	                	$message.= $langs->transnoentities("YouReceiveMailBecauseOfNotification2",$application,$mysoc->name)."\n";
+	                	// Set output language
+	                	$outputlangs = $langs;
+	                	if ($obj->default_lang && $obj->default_lang != $langs->defaultlang)
+	                	{
+	                		$outputlangs = new Translate('', $conf);
+	                		$outputlangs->setDefaultLang($obj->default_lang);
+	                	}
+
+	                    switch ($action) {
+							case 'BILL_VALIDATE':
+								$link='/compta/facture.php?facid='.$object->id;
+								$dir_output = $conf->facture->dir_output;
+								$object_type = 'facture';
+								$mesg = $langs->transnoentitiesnoconv("EMailTextInvoiceValidated",$object->ref);
+								break;
+							case 'ORDER_VALIDATE':
+								$link='/commande/card.php?id='.$object->id;
+								$dir_output = $conf->commande->dir_output;
+								$object_type = 'order';
+								$mesg = $langs->transnoentitiesnoconv("EMailTextOrderValidated",$object->ref);
+								break;
+							case 'PROPAL_VALIDATE':
+								$link='/comm/propal.php?id='.$object->id;
+								$dir_output = $conf->propal->dir_output;
+								$object_type = 'propal';
+								$mesg = $langs->transnoentitiesnoconv("EMailTextProposalValidated",$object->ref);
+								break;
+							case 'FICHINTER_VALIDATE':
+								$link='/fichinter/card.php?id='.$object->id;
+								$dir_output = $conf->facture->dir_output;
+								$object_type = 'ficheinter';
+								$mesg = $langs->transnoentitiesnoconv("EMailTextInterventionValidated",$object->ref);
+								break;
+							case 'ORDER_SUPPLIER_APPROVE':
+								$link='/fourn/commande/card.php?id='.$object->id;
+								$dir_output = $conf->fournisseur->dir_output.'/commande/';
+								$object_type = 'order_supplier';
+								$mesg = $langs->transnoentitiesnoconv("Hello").",\n\n";
+								$mesg.= $langs->transnoentitiesnoconv("EMailTextOrderApprovedBy",$object->ref,$user->getFullName($langs));
+								$mesg.= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n";
+								break;
+							case 'ORDER_SUPPLIER_REFUSE':
+								$link='/fourn/commande/card.php?id='.$object->id;
+								$dir_output = $conf->fournisseur->dir_output.'/commande/';
+								$object_type = 'order_supplier';
+								$mesg = $langs->transnoentitiesnoconv("Hello").",\n\n";
+								$mesg.= $langs->transnoentitiesnoconv("EMailTextOrderRefusedBy",$object->ref,$user->getFullName($langs));
+								$mesg.= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n";
+								break;
+							case 'SHIPPING_VALIDATE':
+								$dir_output = $conf->expedition->dir_output.'/sending/';
+								$object_type = 'order_supplier';
+								$mesg = $langs->transnoentitiesnoconv("EMailTextExpeditionValidated",$object->ref);
+								break;
+						}
+                    	$ref = dol_sanitizeFileName($object->ref);
+						$pdf_path = $dir_output."/".$ref."/".$ref.".pdf";
+						if (! dol_is_file($pdf_path))
+						{
+							// We can't add PDF as it is not generated yet.
+							$filepdf = '';
+						}
+						else
+						{
+							$filepdf = $pdf_path;
+						}
+
+	    				$subject = '['.$application.'] '.$outputlangs->transnoentitiesnoconv("DolibarrNotification");
+
+	                	$message = $outputlangs->transnoentities("YouReceiveMailBecauseOfNotification",$application,$mysoc->name)."\n";
+	                	$message.= $outputlangs->transnoentities("YouReceiveMailBecauseOfNotification2",$application,$mysoc->name)."\n";
 	                	$message.= "\n";
-	                    $message.= $texte;
-	                    // Add link
-	                    $link='';
-	                    switch($objet_type)
-	                    {
-	                    	case 'ficheinter':
-							    $link='/fichinter/card.php?id='.$objet_id;
-	    						break;
-	                    	case 'propal':
-							    $link='/comm/propal.php?id='.$objet_id;
-	    						break;
-	    					case 'facture':
-							    $link='/compta/facture.php?facid='.$objet_id;
-	    						break;
-	                    	case 'order':
-							    $link='/commande/card.php?id='.$objet_id;
-	    						break;
-	    					case 'order_supplier':
-							    $link='/fourn/commande/card.php?id='.$objet_id;
-	    						break;
-	                    }
-						// Define $urlwithroot
-	                    $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
-						$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;			// This is to use external domain name found into config file
-						//$urlwithroot=DOL_MAIN_URL_ROOT;						// This is to use same domain name than current
-	                    if ($link) $message.="\n".$urlwithroot.$link;
-
-	                    $filename = basename($file);
-
-	                    $mimefile=dol_mimetype($file);
-
-	                    $msgishtml=0;
-
-	                    $replyto = $conf->notification->email_from;
+	                    $message.= $mesg;
+	                    if ($link) $message=dol_concatdesc($message,$urlwithroot.$link);
 
 	                    $mailfile = new CMailFile(
 	                        $subject,
@@ -218,26 +287,22 @@ class Notify
 	                        '',
 	                        '',
 	                        0,
-	                        $msgishtml
+	                        -1
 	                    );
 
 	                    if ($mailfile->sendfile())
 	                    {
-	                    	$now=dol_now();
-	                        $sendto = htmlentities($sendto);
-
 	                        $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify (daten, fk_action, fk_contact, objet_type, objet_id, email)";
-	                        $sql.= " VALUES ('".$this->db->idate($now)."', ".$actiondefid.", ".$obj->cid.", '".$objet_type."', ".$objet_id.", '".$this->db->escape($obj->email)."')";
-	                        dol_syslog("Notify::send", LOG_DEBUG);
-	                        if (! $this->db->query($sql) )
+	                        $sql.= " VALUES ('".$this->db->idate(dol_now())."', ".$actiondefid.", ".$obj->cid.", '".$object_type."', ".$object->id.", '".$this->db->escape($obj->email)."')";
+	                        if (! $this->db->query($sql))
 	                        {
 	                            dol_print_error($this->db);
 	                        }
 	                    }
 	                    else
-	                    {
-	                        $this->error=$mailfile->error;
-	                        //dol_syslog("Notify::send ".$this->error, LOG_ERR);
+						{
+							$error++;
+	                        $this->errors[]=$mailfile->error;
 	                    }
 	                }
 	                else
@@ -246,20 +311,129 @@ class Notify
 	                }
 	                $i++;
 	            }
-	            return $i;
             }
             else
 			{
-	            dol_syslog("No notification sent, nothing into notification setup for the thirdparty socid = ".$socid);
-				return 0;
+	            dol_syslog("No notification to thirdparty sent, nothing into notification setup for the thirdparty socid = ".$object->socid);
 			}
         }
         else
        {
-            $this->error=$this->db->lasterror();
+       		$error++;
+            $this->errors[]=$this->db->lasterror();
             return -1;
         }
 
+        // Check notification using fixed email
+        if (! $error)
+        {
+	        $param='NOTIFICATION_FIXEDEMAIL_'.$action;
+	        if (! empty($conf->global->$param))
+	        {
+				$object_type = '';
+		        $link = '';
+        		$num++;
+
+				switch ($action) {
+					case 'BILL_VALIDATE':
+						$link='/compta/facture.php?facid='.$object->id;
+						$dir_output = $conf->facture->dir_output;
+						$object_type = 'facture';
+						$mesg = $langs->transnoentitiesnoconv("EMailTextInvoiceValidated",$object->ref);
+						break;
+					case 'ORDER_VALIDATE':
+						$link='/commande/card.php?id='.$object->id;
+						$dir_output = $conf->commande->dir_output;
+						$object_type = 'order';
+						$mesg = $langs->transnoentitiesnoconv("EMailTextOrderValidated",$object->ref);
+						break;
+					case 'PROPAL_VALIDATE':
+						$link='/comm/propal.php?id='.$object->id;
+						$dir_output = $conf->propal->dir_output;
+						$object_type = 'propal';
+						$mesg = $langs->transnoentitiesnoconv("EMailTextProposalValidated",$object->ref);
+						break;
+					case 'FICHINTER_VALIDATE':
+						$link='/fichinter/card.php?id='.$object->id;
+						$dir_output = $conf->facture->dir_output;
+						$object_type = 'ficheinter';
+						$mesg = $langs->transnoentitiesnoconv("EMailTextInterventionValidated",$object->ref);
+						break;
+					case 'ORDER_SUPPLIER_APPROVE':
+						$link='/fourn/commande/card.php?id='.$object->id;
+						$dir_output = $conf->fournisseur->dir_output.'/commande/';
+						$object_type = 'order_supplier';
+						$mesg = $langs->transnoentitiesnoconv("Hello").",\n\n";
+						$mesg.= $langs->transnoentitiesnoconv("EMailTextOrderApprovedBy",$object->ref,$user->getFullName($langs));
+						$mesg.= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n";
+						break;
+					case 'ORDER_SUPPLIER_REFUSE':
+						$link='/fourn/commande/card.php?id='.$object->id;
+						$dir_output = $conf->fournisseur->dir_output.'/commande/';
+						$object_type = 'order_supplier';
+						$mesg = $langs->transnoentitiesnoconv("Hello").",\n\n";
+						$mesg.= $langs->transnoentitiesnoconv("EMailTextOrderRefusedBy",$object->ref,$user->getFullName($langs));
+						$mesg.= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n";
+						break;
+					case 'SHIPPING_VALIDATE':
+						$dir_output = $conf->expedition->dir_output.'/sending/';
+						$object_type = 'order_supplier';
+						$mesg = $langs->transnoentitiesnoconv("EMailTextExpeditionValidated",$object->ref);
+						break;
+				}
+				$ref = dol_sanitizeFileName($object->ref);
+				$pdf_path = $dir_output."/".$ref."/".$ref.".pdf";
+				if (! dol_is_file($pdf_path))
+				{
+					// We can't add PDF as it is not generated yet.
+					$filepdf = '';
+				}
+				else
+				{
+					$filepdf = $pdf_path;
+				}
+
+				$subject = '['.$application.'] '.$langs->transnoentitiesnoconv("DolibarrNotification");
+
+				$message = $langs->transnoentities("YouReceiveMailBecauseOfNotification",$application,$mysoc->name)."\n";
+				$message.= $langs->transnoentities("YouReceiveMailBecauseOfNotification2",$application,$mysoc->name)."\n";
+				$message.= "\n";
+				$message.= $mesg;
+				if ($link) $message=dol_concatdesc($message,$urlwithroot.$link);
+
+				$mailfile = new CMailFile(
+					$subject,
+					$sendto,
+					$replyto,
+					$message,
+					array($file),
+					array($mimefile),
+					array($filename[count($filename)-1]),
+					'',
+					'',
+					0,
+					-1
+				);
+
+				if ($mailfile->sendfile())
+				{
+					$sql = "INSERT INTO ".MAIN_DB_PREFIX."notify (daten, fk_action, fk_contact, objet_type, objet_id, email)";
+					$sql.= " VALUES ('".$this->db->idate(dol_now())."', ".$actiondefid.", ".$obj->cid.", '".$object_type."', ".$object->id.", '".$this->db->escape($obj->email)."')";
+					if (! $this->db->query($sql))
+					{
+						dol_print_error($this->db);
+					}
+				}
+				else
+				{
+					$error++;
+					$this->errors[]=$mailfile->error;
+				}
+	        }
+        }
+
+		if (! $error) return $num;
+		else return -1 * $error;
     }
 
 }
diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php
index 38e19eb31fd..64e3e9675dc 100644
--- a/htdocs/core/lib/functions.lib.php
+++ b/htdocs/core/lib/functions.lib.php
@@ -4559,6 +4559,8 @@ function picto_from_langcode($codelang)
 {
 	global $langs;
 
+	if (empty($codelang)) return '';
+
 	if ($codelang == 'auto')
 	{
 		return img_picto_common($langs->trans('AutoDetectLang'), 'flags/int.png');
diff --git a/htdocs/core/triggers/interface_50_modNotification_Notification.class.php b/htdocs/core/triggers/interface_50_modNotification_Notification.class.php
index 368f7bdeeb8..940e3a1712d 100644
--- a/htdocs/core/triggers/interface_50_modNotification_Notification.class.php
+++ b/htdocs/core/triggers/interface_50_modNotification_Notification.class.php
@@ -60,70 +60,12 @@ class InterfaceNotification extends DolibarrTriggers
 	{
 		if (empty($conf->notification->enabled)) return 0;     // Module not active, we do nothing
 
-		require_once DOL_DOCUMENT_ROOT .'/core/class/notify.class.php';
-
-		$langs->load("other");
-
-		switch ($action) {
-			case 'BILL_VALIDATE':
-				$dir_output = $conf->facture->dir_output;
-				$object_type = 'facture';
-				$mesg = $langs->transnoentitiesnoconv("EMailTextInvoiceValidated",$object->ref);
-				break;
-			case 'ORDER_VALIDATE':
-				$dir_output = $conf->commande->dir_output;
-				$object_type = 'order';
-				$mesg = $langs->transnoentitiesnoconv("EMailTextOrderValidated",$object->ref);
-				break;
-			case 'PROPAL_VALIDATE':
-				$dir_output = $conf->propal->dir_output;
-				$object_type = 'propal';
-				$mesg = $langs->transnoentitiesnoconv("EMailTextProposalValidated",$object->ref);
-				break;
-			case 'FICHINTER_VALIDATE':
-				$dir_output = $conf->facture->dir_output;
-				$object_type = 'ficheinter';
-				$mesg = $langs->transnoentitiesnoconv("EMailTextInterventionValidated",$object->ref);
-				break;
-			case 'ORDER_SUPPLIER_APPROVE':
-				$dir_output = $conf->fournisseur->dir_output.'/commande/';
-				$object_type = 'order_supplier';
-				$mesg = $langs->transnoentitiesnoconv("Hello").",\n\n";
-				$mesg.= $langs->transnoentitiesnoconv("EMailTextOrderApprovedBy",$object->ref,$user->getFullName($langs));
-				$mesg.= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n";
-				break;
-			case 'ORDER_SUPPLIER_REFUSE':
-				$dir_output = $conf->fournisseur->dir_output.'/commande/';
-				$object_type = 'order_supplier';
-				$mesg = $langs->transnoentitiesnoconv("Hello").",\n\n";
-				$mesg.= $langs->transnoentitiesnoconv("EMailTextOrderRefusedBy",$object->ref,$user->getFullName($langs));
-				$mesg.= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n";
-				break;
-			case 'SHIPPING_VALIDATE':
-				$dir_output = $conf->expedition->dir_output.'/sending/';
-				$object_type = 'order_supplier';
-				$mesg = $langs->transnoentitiesnoconv("EMailTextExpeditionValidated",$object->ref);
-				break;
-
-			default:
-				return 0;
-
-		}
-
 		dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id);
 
-		$ref = dol_sanitizeFileName($object->ref);
-		$pdf_path = "$dir_output/$ref/$ref.pdf";
-
-		if (!file_exists($pdf_path)) {
-			// We can't add PDF as it is not generated yet.
-			$filepdf = '';
-		} else {
-			$filepdf = $pdf_path;
-		}
+		require_once DOL_DOCUMENT_ROOT .'/core/class/notify.class.php';
 
 		$notify = new Notify($this->db);
-		$notify->send($action, $object->socid, $mesg, $object_type, $object->id, $filepdf);
+		$notify->send($action, $object);
 
 		return 1;
     }
diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang
index fe28b967d67..15bf8da0833 100644
--- a/htdocs/langs/en_US/admin.lang
+++ b/htdocs/langs/en_US/admin.lang
@@ -484,7 +484,7 @@ Module500Desc=Management of special expenses like taxes, social contribution, di
 Module510Name=Salaries
 Module510Desc=Management of employees salaries and payments
 Module600Name=Notifications
-Module600Desc=Send notifications by email on some Dolibarr business events to third party contacts
+Module600Desc=Send EMail notifications on some Dolibarr business events to third-party contacts (setup defined on each thirdparty)
 Module700Name=Donations
 Module700Desc=Donation management
 Module1200Name=Mantis
@@ -1074,7 +1074,7 @@ ModuleCompanyCodeAquarium=Return an accountancy code built by:<br>%s followed by
 ModuleCompanyCodePanicum=Return an empty accountancy code.
 ModuleCompanyCodeDigitaria=Accountancy code depends on third party code. The code is composed of the character "C" in the first position followed by the first 5 characters of the third party code.  
 UseNotifications=Use notifications
-NotificationsDesc=EMails notifications feature allows you to silently send automatic mail, for some Dolibarr events, to third parties (customers or suppliers) that are configured to. Choice of active notification and targets contacts is made one third party at time.
+NotificationsDesc=EMails notifications feature allows you to silently send automatic mail, for some Dolibarr events. Targets of notifications can be defined:<br>* per third parties contacts (customers or suppliers), one third party at time.<br>* or by setting a global target email address on this page.
 ModelModules=Documents templates
 DocumentModelOdt=Generate documents from OpenDocuments templates (.ODT or .ODS files for OpenOffice, KOffice, TextEdit,...)
 WatermarkOnDraft=Watermark on draft document
@@ -1384,7 +1384,8 @@ MailingEMailError=Return EMail (Errors-to) for emails with errors
 ##### Notification #####
 NotificationSetup=EMail notification module setup
 NotificationEMailFrom=Sender EMail (From) for emails sent for notifications
-ListOfAvailableNotifications=List of available notifications (This list depends on activated modules)
+ListOfAvailableNotifications=List of events you can set notification on, for each thirdparty (go into thirdparty card to setup) or by setting a fixed email (List depends on activated modules)
+FixedEmailTarget=Fixed email target
 ##### Sendings #####
 SendingsSetup=Sending module setup
 SendingsReceiptModel=Sending receipt model
diff --git a/htdocs/langs/en_US/other.lang b/htdocs/langs/en_US/other.lang
index 10e4403f4fb..1e74b72f635 100644
--- a/htdocs/langs/en_US/other.lang
+++ b/htdocs/langs/en_US/other.lang
@@ -47,6 +47,7 @@ Notify_PROJECT_CREATE=Project creation
 Notify_TASK_CREATE=Task created
 Notify_TASK_MODIFY=Task modified
 Notify_TASK_DELETE=Task deleted
+SeeModuleSetup=See module setup
 NbOfAttachedFiles=Number of attached files/documents
 TotalSizeOfAttachedFiles=Total size of attached files/documents
 MaxSize=Maximum size
diff --git a/htdocs/societe/notify/card.php b/htdocs/societe/notify/card.php
index 8604b229134..12cdb64c790 100644
--- a/htdocs/societe/notify/card.php
+++ b/htdocs/societe/notify/card.php
@@ -212,7 +212,7 @@ if ($result > 0)
     // Line with titles
     print '<table width="100%" class="noborder">';
     print '<tr class="liste_titre">';
-    print_liste_field_titre($langs->trans("Contact"),$_SERVER["PHP_SELF"],"c.lastname",'',$param,'"width="45%"',$sortfield,$sortorder);
+    print_liste_field_titre($langs->trans("Target"),$_SERVER["PHP_SELF"],"c.lastname",'',$param,'"width="45%"',$sortfield,$sortorder);
     print_liste_field_titre($langs->trans("Action"),$_SERVER["PHP_SELF"],"a.titre",'',$param,'"width="35%"',$sortfield,$sortorder);
     print_liste_field_titre($langs->trans("Type"),$_SERVER["PHP_SELF"],"",'',$param,'"width="10%"',$sortfield,$sortorder);
     print_liste_field_titre('');
@@ -265,13 +265,40 @@ if ($result > 0)
     // Line with titles
     print '<table width="100%" class="noborder">';
     print '<tr class="liste_titre">';
-    print_liste_field_titre($langs->trans("Contact"),$_SERVER["PHP_SELF"],"c.lastname",'',$param,'"width="45%"',$sortfield,$sortorder);
+    print_liste_field_titre($langs->trans("Target"),$_SERVER["PHP_SELF"],"c.lastname",'',$param,'"width="45%"',$sortfield,$sortorder);
     print_liste_field_titre($langs->trans("Action"),$_SERVER["PHP_SELF"],"a.titre",'',$param,'"width="35%"',$sortfield,$sortorder);
     print_liste_field_titre($langs->trans("Type"),$_SERVER["PHP_SELF"],"",'',$param,'"width="10%"',$sortfield,$sortorder);
     print_liste_field_titre('','','');
     print '</tr>';
 
-    // List of notifications for contacts
+    // List of notifications enabled for fixed email
+    foreach($conf->global as $key => $val)
+    {
+    	if (! preg_match('/^NOTIFICATION_FIXEDEMAIL_(.*)/', $key, $reg)) continue;
+    	//print $key.' - '.$val.' - '.$reg[1].'<br>';
+		print '<tr '.$bc[$var].'><td>'.$val;
+		if (isValidEmail($val))
+		{
+			print ' &lt;'.$val.'&gt;';
+		}
+		else
+		{
+			$langs->load("errors");
+			print ' &nbsp; '.img_warning().' '.$langs->trans("ErrorBadEMail",$val);
+		}
+		print '</td>';
+		print '<td>';
+		$label=($langs->trans("Notify_".$reg[1])!="Notify_".$reg[1]?$langs->trans("Notify_".$reg[1]):$reg[1]);
+		print $label;
+		print '</td>';
+		print '<td>';
+		print $langs->trans("Email");
+		print '</td>';
+		print '<td align="right">'.$langs->trans("SeeModuleSetup").'</td>';
+		print '</tr>';
+    }
+
+    // List of notifications enabled for contacts
     $sql = "SELECT n.rowid, n.type,";
     $sql.= " a.code, a.label,";
     $sql.= " c.rowid as contactid, c.lastname, c.firstname, c.email";
@@ -343,7 +370,7 @@ if ($result > 0)
     // Line with titles
     print '<table width="100%" class="noborder">';
     print '<tr class="liste_titre">';
-    print_liste_field_titre($langs->trans("Contact"),$_SERVER["PHP_SELF"],"c.lastname",'',$param,'',$sortfield,$sortorder);
+    print_liste_field_titre($langs->trans("Target"),$_SERVER["PHP_SELF"],"c.lastname",'',$param,'',$sortfield,$sortorder);
     print_liste_field_titre($langs->trans("Action"),$_SERVER["PHP_SELF"],"a.titre",'',$param,'',$sortfield,$sortorder);
     print_liste_field_titre($langs->trans("Date"),$_SERVER["PHP_SELF"],"a.daten",'',$param,'align="right"',$sortfield,$sortorder);
     print '</tr>';
-- 
GitLab