mailing-send.php 17 KB

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