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