mailing-send.php 17 KB

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