mailing-send.php 17 KB

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