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