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