dolibarr  13.0.2
mailing-send.php
Go to the documentation of this file.
1 #!/usr/bin/env php
2 <?php
3 /*
4  * Copyright (C) 2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
5  * Copyright (C) 2005-2013 Laurent Destailleur <eldy@users.sourceforge.net>
6  * Copyright (C) 2005-2016 Regis Houssin <regis.houssin@inodbox.com>
7  * Copyright (C) 2019 Nicolas ZABOURI <info@inovea-conseil.com>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program. If not, see <https://www.gnu.org/licenses/>.
21  */
22 
29 if (!defined('NOSESSION')) define('NOSESSION', '1');
30 
31 $sapi_type = php_sapi_name();
32 $script_file = basename(__FILE__);
33 $path = __DIR__.'/';
34 
35 // Test if batch mode
36 if (substr($sapi_type, 0, 3) == 'cgi') {
37  echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
38  exit(-1);
39 }
40 
41 if (!isset($argv[1]) || !$argv[1]) {
42  print "Usage: ".$script_file." (ID_MAILING|all) [userloginforsignature] [maxnbofemails]\n";
43  exit(-1);
44 }
45 
46 $id = $argv[1];
47 
48 if (isset($argv[2]) || !empty($argv[2])) $login = $argv[2];
49 else $login = '';
50 
51 $max = 0;
52 
53 if (isset($argv[3]) || !empty($argv[3])) $max = $argv[3];
54 
55 
56 require_once $path."../../htdocs/master.inc.php";
57 require_once DOL_DOCUMENT_ROOT."/core/class/CMailFile.class.php";
58 require_once DOL_DOCUMENT_ROOT."/comm/mailing/class/mailing.class.php";
59 
60 // Global variables
61 $version = DOL_VERSION;
62 $error = 0;
63 
64 if (empty($conf->global->MAILING_LIMIT_SENDBYCLI))
65 {
66  $conf->global->MAILING_LIMIT_SENDBYCLI = 0;
67 }
68 
69 
70 /*
71  * Main
72  */
73 
74 @set_time_limit(0);
75 print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
76 
77 if (!empty($conf->global->MAILING_DELAY)) {
78  print 'A delay of '.((float) $conf->global->MAILING_DELAY * 1000000).' millisecond has been set between each email'."\n";
79 }
80 
81 if ($conf->global->MAILING_LIMIT_SENDBYCLI == '-1') {}
82 
83 $user = new User($db);
84 // for signature, we use user send as parameter
85 if (!empty($login))
86  $user->fetch('', $login);
87 
88 // We get list of emailing id to process
89 $sql = "SELECT m.rowid";
90 $sql .= " FROM ".MAIN_DB_PREFIX."mailing as m";
91 $sql .= " WHERE m.statut IN (1,2)";
92 if ($id != 'all') {
93  $sql .= " AND m.rowid= ".$id;
94  $sql .= " LIMIT 1";
95 }
96 
97 $resql = $db->query($sql);
98 if ($resql) {
99  $num = $db->num_rows($resql);
100  $j = 0;
101 
102  if ($num) {
103  for ($j = 0; $j < $num; $j++) {
104  $obj = $db->fetch_object($resql);
105 
106  dol_syslog("Process mailing with id ".$obj->rowid);
107  print "Process mailing with id ".$obj->rowid."\n";
108 
109  $emailing = new Mailing($db);
110  $emailing->fetch($obj->rowid);
111 
112  $upload_dir = $conf->mailing->dir_output."/".get_exdir($emailing->id, 2, 0, 1, $emailing, 'mailing');
113 
114  $id = $emailing->id;
115  $subject = $emailing->sujet;
116  $message = $emailing->body;
117  $from = $emailing->email_from;
118  $replyto = $emailing->email_replyto;
119  $errorsto = $emailing->email_errorsto;
120  // Le message est-il en html
121  $msgishtml = - 1; // Unknown by default
122  if (preg_match('/[\s\t]*<html>/i', $message))
123  $msgishtml = 1;
124 
125  $nbok = 0;
126  $nbko = 0;
127 
128  // On choisit les mails non deja envoyes pour ce mailing (statut=0)
129  // ou envoyes en erreur (statut=-1)
130  $sql2 = "SELECT mc.rowid, mc.fk_mailing, mc.lastname, mc.firstname, mc.email, mc.other, mc.source_url, mc.source_id, mc.source_type, mc.tag";
131  $sql2 .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc";
132  $sql2 .= " WHERE mc.statut < 1 AND mc.fk_mailing = ".((int) $id);
133  if ($conf->global->MAILING_LIMIT_SENDBYCLI > 0 && empty($max)) {
134  $sql2 .= " LIMIT ".$conf->global->MAILING_LIMIT_SENDBYCLI;
135  } elseif ($conf->global->MAILING_LIMIT_SENDBYCLI > 0 && $max > 0) {
136  $sql2 .= " LIMIT ".min($conf->global->MAILING_LIMIT_SENDBYCLI, $max);
137  } elseif ($max > 0) {
138  $sql2 .= " LIMIT ".$max;
139  }
140 
141  $resql2 = $db->query($sql2);
142  if ($resql2) {
143  $num2 = $db->num_rows($resql2);
144  dol_syslog("Nb of targets = ".$num2, LOG_DEBUG);
145  print "Nb of targets = ".$num2."\n";
146 
147  if ($num2) {
148  $now = dol_now();
149 
150  // Positionne date debut envoi
151  $sqlstartdate = "UPDATE ".MAIN_DB_PREFIX."mailing SET date_envoi='".$db->idate($now)."' WHERE rowid=".((int) $id);
152  $resqlstartdate = $db->query($sqlstartdate);
153  if (!$resqlstartdate) {
154  dol_print_error($db);
155  $error++;
156  }
157 
158  // Look on each email and sent message
159  $i = 0;
160  while ($i < $num2) {
161  // Here code is common with same loop ino card.php
162  $res = 1;
163  $now = dol_now();
164 
165  $obj = $db->fetch_object($resql2);
166 
167  // sendto en RFC2822
168  $sendto = str_replace(',', ' ', dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">");
169 
170  // Make subtsitutions on topic and body
171  $other = explode(';', $obj->other);
172  $tmpfield = explode('=', $other[0], 2);
173  $other1 = (isset($tmpfield[1]) ? $tmpfield[1] : $tmpfield[0]);
174  $tmpfield = explode('=', $other[1], 2);
175  $other2 = (isset($tmpfield[1]) ? $tmpfield[1] : $tmpfield[0]);
176  $tmpfield = explode('=', $other[2], 2);
177  $other3 = (isset($tmpfield[1]) ? $tmpfield[1] : $tmpfield[0]);
178  $tmpfield = explode('=', $other[3], 2);
179  $other4 = (isset($tmpfield[1]) ? $tmpfield[1] : $tmpfield[0]);
180  $tmpfield = explode('=', $other[4], 2);
181  $other5 = (isset($tmpfield[1]) ? $tmpfield[1] : $tmpfield[0]);
182  $signature = ((!empty($user->signature) && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? $user->signature : '');
183 
184  $object = null; // Not defined with mass emailing
185  $parameters = array('mode' => 'emailing');
186  $substitutionarray = getCommonSubstitutionArray($langs, 0, array('object', 'objectamount'), $object); // Note: On mass emailing, this is null because we don't know object
187 
188  // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions)
189  $substitutionarray['__ID__'] = $obj->source_id;
190  $substitutionarray['__EMAIL__'] = $obj->email;
191  $substitutionarray['__LASTNAME__'] = $obj->lastname;
192  $substitutionarray['__FIRSTNAME__'] = $obj->firstname;
193  $substitutionarray['__MAILTOEMAIL__'] = '<a href="mailto:'.$obj->email.'">'.$obj->email.'</a>';
194  $substitutionarray['__OTHER1__'] = $other1;
195  $substitutionarray['__OTHER2__'] = $other2;
196  $substitutionarray['__OTHER3__'] = $other3;
197  $substitutionarray['__OTHER4__'] = $other4;
198  $substitutionarray['__OTHER5__'] = $other5;
199  $substitutionarray['__USER_SIGNATURE__'] = $signature; // Signature is empty when ran from command line or taken from user in parameter)
200  $substitutionarray['__SIGNATURE__'] = $signature; // For backward compatibility
201  $substitutionarray['__CHECK_READ__'] = '<img src="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?tag='.$obj->tag.'&securitykey='.urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY).'" width="1" height="1" style="width:1px;height:1px" border="0"/>';
202  $substitutionarray['__UNSUBSCRIBE__'] = '<a href="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-unsubscribe.php?tag='.$obj->tag.'&unsuscrib=1&securitykey='.urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY).'" target="_blank">'.$langs->trans("MailUnsubcribe").'</a>';
203 
204  $onlinepaymentenabled = 0;
205  if (!empty($conf->paypal->enabled))
206  $onlinepaymentenabled++;
207  if (!empty($conf->paybox->enabled))
208  $onlinepaymentenabled++;
209  if (!empty($conf->stripe->enabled))
210  $onlinepaymentenabled++;
211  if ($onlinepaymentenabled && !empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
212  $substitutionarray['__SECUREKEYPAYMENT__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2);
213  if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
214  $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2);
215  $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2);
216  $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2);
217  $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2);
218  } else {
219  $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'membersubscription'.$obj->source_id, 2);
220  $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'order'.$obj->source_id, 2);
221  $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'invoice'.$obj->source_id, 2);
222  $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.'contractline'.$obj->source_id, 2);
223  }
224  }
225  /* For backward compatibility */
226  if (!empty($conf->paypal->enabled) && !empty($conf->global->PAYPAL_SECURITY_TOKEN)) {
227  $substitutionarray['__SECUREKEYPAYPAL__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2);
228 
229  if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE))
230  $substitutionarray['__SECUREKEYPAYPAL_MEMBER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2);
231  else $substitutionarray['__SECUREKEYPAYPAL_MEMBER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'membersubscription'.$obj->source_id, 2);
232 
233  if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE))
234  $substitutionarray['__SECUREKEYPAYPAL_ORDER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2);
235  else $substitutionarray['__SECUREKEYPAYPAL_ORDER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'order'.$obj->source_id, 2);
236 
237  if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE))
238  $substitutionarray['__SECUREKEYPAYPAL_INVOICE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2);
239  else $substitutionarray['__SECUREKEYPAYPAL_INVOICE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'invoice'.$obj->source_id, 2);
240 
241  if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE))
242  $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2);
243  else $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN.'contractline'.$obj->source_id, 2);
244  }
245 
246  complete_substitutions_array($substitutionarray, $langs);
247  $newsubject = make_substitutions($subject, $substitutionarray);
248  $newmessage = make_substitutions($message, $substitutionarray);
249 
250  $substitutionisok = true;
251 
252  $arr_file = array();
253  $arr_mime = array();
254  $arr_name = array();
255  $arr_css = array();
256 
257  $listofpaths = dol_dir_list($upload_dir, 'all', 0, '', '', 'name', SORT_ASC, 0);
258 
259  if (count($listofpaths))
260  {
261  foreach ($listofpaths as $key => $val)
262  {
263  $arr_file[] = $listofpaths[$key]['fullname'];
264  $arr_mime[] = dol_mimetype($listofpaths[$key]['name']);
265  $arr_name[] = $listofpaths[$key]['name'];
266  }
267  }
268  // Fabrication du mail
269  $trackid = 'emailing-'.$obj->fk_mailing.'-'.$obj->rowid;
270  $mail = new CMailFile($newsubject, $sendto, $from, $newmessage, $arr_file, $arr_mime, $arr_name, '', '', 0, $msgishtml, $errorsto, $arr_css, $trackid, '', 'emailing');
271 
272  if ($mail->error) {
273  $res = 0;
274  }
275  if (!$substitutionisok) {
276  $mail->error = 'Some substitution failed';
277  $res = 0;
278  }
279 
280  // Send Email
281  if ($res) {
282  $res = $mail->sendfile();
283  }
284 
285  if ($res) {
286  // Mail successful
287  $nbok++;
288 
289  dol_syslog("ok for emailing id ".$id." #".$i.($mail->error ? ' - '.$mail->error : ''), LOG_DEBUG);
290 
291  // Note: If emailing is 100 000 targets, 100 000 entries are added, so we don't enter events for each target here
292  // We must union table llx_mailing_taget for event tab OR enter 1 event with a special table link (id of email in event)
293  // Run trigger
294  /*
295  * if ($obj->source_type == 'contact')
296  * {
297  * $emailing->sendtoid = $obj->source_id;
298  * }
299  * if ($obj->source_type == 'thirdparty')
300  * {
301  * $emailing->socid = $obj->source_id;
302  * }
303  * // Call trigger
304  * $result=$emailing->call_trigger('EMAILING_SENTBYMAIL',$user);
305  * if ($result < 0) $error++;
306  * // End call triggers
307  */
308 
309  $sqlok = "UPDATE ".MAIN_DB_PREFIX."mailing_cibles";
310  $sqlok .= " SET statut=1, date_envoi='".$db->idate($now)."' WHERE rowid=".$obj->rowid;
311  $resqlok = $db->query($sqlok);
312  if (!$resqlok) {
313  dol_print_error($db);
314  $error++;
315  } else {
316  // if cheack read is use then update prospect contact status
317  if (strpos($message, '__CHECK_READ__') !== false) {
318  // Update status communication of thirdparty prospect
319  $sqlx = "UPDATE ".MAIN_DB_PREFIX."societe SET fk_stcomm=2 WHERE rowid IN (SELECT source_id FROM ".MAIN_DB_PREFIX."mailing_cibles WHERE rowid=".$obj->rowid.")";
320  dol_syslog("card.php: set prospect thirdparty status", LOG_DEBUG);
321  $resqlx = $db->query($sqlx);
322  if (!$resqlx) {
323  dol_print_error($db);
324  $error++;
325  }
326 
327  // Update status communication of contact prospect
328  $sqlx = "UPDATE ".MAIN_DB_PREFIX."societe SET fk_stcomm=2 WHERE rowid IN (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."socpeople AS sc INNER JOIN ".MAIN_DB_PREFIX."mailing_cibles AS mc ON mc.rowid=".$obj->rowid." AND mc.source_type = 'contact' AND mc.source_id = sc.rowid)";
329  dol_syslog("card.php: set prospect contact status", LOG_DEBUG);
330 
331  $resqlx = $db->query($sqlx);
332  if (!$resqlx) {
333  dol_print_error($db);
334  $error++;
335  }
336  }
337 
338  if (!empty($conf->global->MAILING_DELAY)) {
339  usleep((float) $conf->global->MAILING_DELAY * 1000000);
340  }
341  }
342  } else {
343  // Mail failed
344  $nbko++;
345 
346  dol_syslog("error for emailing id ".$id." #".$i.($mail->error ? ' - '.$mail->error : ''), LOG_DEBUG);
347 
348  $sqlerror = "UPDATE ".MAIN_DB_PREFIX."mailing_cibles";
349  $sqlerror .= " SET statut=-1, date_envoi='".$db->idate($now)."' WHERE rowid=".$obj->rowid;
350  $resqlerror = $db->query($sqlerror);
351  if (!$resqlerror) {
352  dol_print_error($db);
353  $error++;
354  }
355  }
356 
357  $i++;
358  }
359  } else {
360  $mesg = "Emailing id ".$id." has no recipient to target";
361  print $mesg."\n";
362  dol_syslog($mesg, LOG_ERR);
363  }
364 
365  // Loop finished, set global statut of mail
366  $statut = 2;
367  if (!$nbko)
368  $statut = 3;
369 
370  $sqlenddate = "UPDATE ".MAIN_DB_PREFIX."mailing SET statut=".$statut." WHERE rowid=".$id;
371 
372  dol_syslog("update global status", LOG_DEBUG);
373  print "Update status of emailing id ".$id." to ".$statut."\n";
374  $resqlenddate = $db->query($sqlenddate);
375  if (!$resqlenddate) {
376  dol_print_error($db);
377  $error++;
378  }
379  } else {
380  dol_print_error($db);
381  $error++;
382  }
383  }
384  } else {
385  $mesg = "No validated emailing id to send found.";
386  print $mesg."\n";
387  dol_syslog($mesg, LOG_ERR);
388  $error++;
389  }
390 } else {
391  dol_print_error($db);
392  $error++;
393 }
394 
395 exit($error);
dol_hash($chain, $type= '0')
Returns a hash of a string.
dol_now($mode= 'auto')
Return date for now.
Class to manage Dolibarr users.
Definition: user.class.php:44
dol_getmypid()
Return getmypid() or random PID when function is disabled Some web hosts disable this php function fo...
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null)
Return array of possible common substitutions.
dol_mimetype($file, $default= 'application/octet-stream', $mode=0)
Return mime type of a file.
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,$sendto,$replyto,$message,$filepath,$mimetype,$filename,$cc,$ccc,$deliveryreceipt,$msgishtml,$errors_to,$css,$trackid,$moreinheader,$sendcontext,$replyto); $mailfile-&gt;sendfile();.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart= '')
Return a path to have a the directory according to object where files are stored. ...
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:60
Class to manage emailings module.
print
Draft customers invoices.
Definition: index.php:89
if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) if(!empty($conf->don->enabled)&&$user->rights->don->lire) if(!empty($conf->tax->enabled)&&$user->rights->tax->charges->lire) if(!empty($conf->facture->enabled)&&!empty($conf->commande->enabled)&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1232
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
make_substitutions($text, $substitutionarray, $outputlangs=null)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=&gt;newva...
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the &quot;subst...