Merge pull request #15321 from yashodha/dev_1065
[civicrm-core.git] / CRM / Mailing / BAO / MailingJob.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
6a488035
TO
32 */
33
34require_once 'Mail.php';
4c6ce474
EM
35
36/**
37 * Class CRM_Mailing_BAO_MailingJob
38 */
9da8dc8c 39class CRM_Mailing_BAO_MailingJob extends CRM_Mailing_DAO_MailingJob {
7da04cde 40 const MAX_CONTACTS_TO_PROCESS = 1000;
6a488035 41
97b7d4a0 42 /**
a335f6b2 43 * (Dear God Why) Keep a global count of mails processed within the current
97b7d4a0
TO
44 * request.
45 *
97b7d4a0
TO
46 * @var int
47 */
7e8c8317 48 public static $mailsProcessed = 0;
97b7d4a0 49
6a488035 50 /**
fe482240 51 * Class constructor.
6a488035 52 */
00be9182 53 public function __construct() {
6a488035
TO
54 parent::__construct();
55 }
56
af4c09bc 57 /**
dbb0d30b 58 * Create mailing job.
59 *
c490a46a 60 * @param array $params
af4c09bc 61 *
dbb0d30b 62 * @return \CRM_Mailing_BAO_MailingJob
63 * @throws \CRM_Core_Exception
af4c09bc 64 */
7e8c8317 65 public static function create($params) {
f487e358 66 if (empty($params['id']) && empty($params['mailing_id'])) {
85d20752
TO
67 throw new CRM_Core_Exception("Failed to create job: Unknown mailing ID");
68 }
f487e358 69 $op = empty($params['id']) ? 'create' : 'edit';
70 CRM_Utils_Hook::pre($op, 'MailingJob', CRM_Utils_Array::value('id', $params), $params);
71
72 $jobDAO = new CRM_Mailing_BAO_MailingJob();
73 $jobDAO->copyValues($params, TRUE);
74 $jobDAO->save();
2dd8a2cb 75 if (!empty($params['mailing_id']) && empty('is_calling_function_updated_to_reflect_deprecation')) {
f487e358 76 CRM_Mailing_BAO_Mailing::getRecipients($params['mailing_id']);
77 }
78 CRM_Utils_Hook::post($op, 'MailingJob', $jobDAO->id, $jobDAO);
79 return $jobDAO;
6a488035 80 }
af4c09bc 81
6a488035 82 /**
dbb0d30b 83 * Initiate all pending/ready jobs.
6a488035 84 *
100fef9d 85 * @param array $testParams
dbb0d30b 86 * @param string $mode
87 *
88 * @return bool|null
6a488035
TO
89 */
90 public static function runJobs($testParams = NULL, $mode = NULL) {
9da8dc8c 91 $job = new CRM_Mailing_BAO_MailingJob();
6a488035 92
353ffa53 93 $jobTable = CRM_Mailing_DAO_MailingJob::getTableName();
6a488035 94 $mailingTable = CRM_Mailing_DAO_Mailing::getTableName();
57873f1b 95 $mailerBatchLimit = Civi::settings()->get('mailerBatchLimit');
6a488035
TO
96
97 if (!empty($testParams)) {
98 $query = "
99 SELECT *
100 FROM $jobTable
101 WHERE id = {$testParams['job_id']}";
102 $job->query($query);
103 }
104 else {
105 $currentTime = date('YmdHis');
353ffa53
TO
106 $mailingACL = CRM_Mailing_BAO_Mailing::mailingACL('m');
107 $domainID = CRM_Core_Config::domainID();
6a488035
TO
108
109 $modeClause = 'AND m.sms_provider_id IS NULL';
110 if ($mode == 'sms') {
111 $modeClause = 'AND m.sms_provider_id IS NOT NULL';
112 }
113
114 // Select the first child job that is scheduled
115 // CRM-6835
116 $query = "
117 SELECT j.*
118 FROM $jobTable j,
119 $mailingTable m
120 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
121 {$modeClause}
122 AND j.is_test = 0
123 AND ( ( j.start_date IS null
124 AND j.scheduled_date <= $currentTime
125 AND j.status = 'Scheduled' )
126 OR ( j.status = 'Running'
127 AND j.end_date IS null ) )
128 AND (j.job_type = 'child')
129 AND {$mailingACL}
ce5f98aa 130 ORDER BY j.scheduled_date ASC,
daacf196 131 j.id
6a488035
TO
132 ";
133
134 $job->query($query);
135 }
136
6a488035
TO
137 while ($job->fetch()) {
138 // still use job level lock for each child job
83617886 139 $lock = Civi::lockManager()->acquire("data.mailing.job.{$job->id}");
6a488035
TO
140 if (!$lock->isAcquired()) {
141 continue;
142 }
143
144 // for test jobs we do not change anything, since its on a short-circuit path
145 if (empty($testParams)) {
146 // we've got the lock, but while we were waiting and processing
147 // other emails, this job might have changed under us
148 // lets get the job status again and check
1a5727bd 149 $job->status = CRM_Core_DAO::getFieldValue(
cbe30f5a 150 'CRM_Mailing_DAO_MailingJob',
6a488035 151 $job->id,
6606b2e1
DL
152 'status',
153 'id',
154 TRUE
6a488035
TO
155 );
156
1a5727bd
DL
157 if (
158 $job->status != 'Running' &&
6a488035
TO
159 $job->status != 'Scheduled'
160 ) {
161 // this includes Cancelled and other statuses, CRM-4246
162 $lock->release();
163 continue;
164 }
165 }
166
167 /* Queue up recipients for the child job being launched */
168
169 if ($job->status != 'Running') {
170 $transaction = new CRM_Core_Transaction();
171
172 // have to queue it up based on the offset and limits
173 // get the parent ID, and limit and offset
174 $job->queue($testParams);
175
f487e358 176 // Update to show job has started.
177 self::create([
178 'id' => $job->id,
179 'start_date' => date('YmdHis'),
180 'status' => 'Running',
181 ]);
6a488035
TO
182
183 $transaction->commit();
184 }
185
186 // Get the mailer
6a488035 187 if ($mode === NULL) {
048222df 188 $mailer = \Civi::service('pear_mail');
6a488035
TO
189 }
190 elseif ($mode == 'sms') {
be2fb01f 191 $mailer = CRM_SMS_Provider::singleton(['mailing_id' => $job->mailing_id]);
6a488035
TO
192 }
193
194 // Compose and deliver each child job
aa4343bc 195 if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_DELIVER')) {
be2fb01f 196 $isComplete = Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_DELIVER, [$job, $mailer, $testParams]);
aa4343bc
TO
197 }
198 else {
199 $isComplete = $job->deliver($mailer, $testParams);
200 }
6a488035
TO
201
202 CRM_Utils_Hook::post('create', 'CRM_Mailing_DAO_Spool', $job->id, $isComplete);
203
204 // Mark the child complete
205 if ($isComplete) {
25606795 206 // Finish the job.
6a488035
TO
207
208 $transaction = new CRM_Core_Transaction();
f487e358 209 self::create(['id' => $job->id, 'end_date' => date('YmdHis'), 'status' => 'Complete']);
6a488035
TO
210 $transaction->commit();
211
212 // don't mark the mailing as complete
213 }
214
215 // Release the child joblock
216 $lock->release();
217
218 if ($testParams) {
219 return $isComplete;
220 }
57873f1b
J
221
222 // CRM-17629: Stop processing jobs if mailer batch limit reached
223 if ($mailerBatchLimit > 0 && self::$mailsProcessed >= $mailerBatchLimit) {
224 break;
225 }
226
6a488035
TO
227 }
228 }
229
e0ef6999 230 /**
25606795
SB
231 * Post process to determine if the parent job
232 * as well as the mailing is complete after the run.
e0ef6999
EM
233 * @param null $mode
234 */
6a488035
TO
235 public static function runJobs_post($mode = NULL) {
236
9da8dc8c 237 $job = new CRM_Mailing_BAO_MailingJob();
6a488035
TO
238
239 $mailing = new CRM_Mailing_BAO_Mailing();
240
353ffa53
TO
241 $config = CRM_Core_Config::singleton();
242 $jobTable = CRM_Mailing_DAO_MailingJob::getTableName();
6a488035
TO
243 $mailingTable = CRM_Mailing_DAO_Mailing::getTableName();
244
245 $currentTime = date('YmdHis');
353ffa53
TO
246 $mailingACL = CRM_Mailing_BAO_Mailing::mailingACL('m');
247 $domainID = CRM_Core_Config::domainID();
6a488035
TO
248
249 $query = "
250 SELECT j.*
251 FROM $jobTable j,
252 $mailingTable m
253 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
254 AND j.is_test = 0
255 AND j.scheduled_date <= $currentTime
256 AND j.status = 'Running'
257 AND j.end_date IS null
258 AND (j.job_type != 'child' OR j.job_type is NULL)
259 ORDER BY j.scheduled_date,
260 j.start_date";
261
262 $job->query($query);
263
264 // For each parent job that is running, let's look at their child jobs
265 while ($job->fetch()) {
266
9da8dc8c 267 $child_job = new CRM_Mailing_BAO_MailingJob();
6a488035
TO
268
269 $child_job_sql = "
270 SELECT count(j.id)
271 FROM civicrm_mailing_job j, civicrm_mailing m
272 WHERE m.id = j.mailing_id
273 AND j.job_type = 'child'
274 AND j.parent_id = %1
275 AND j.status <> 'Complete'";
be2fb01f 276 $params = [1 => [$job->id, 'Integer']];
6a488035
TO
277
278 $anyChildLeft = CRM_Core_DAO::singleValueQuery($child_job_sql, $params);
279
280 // all of the child jobs are complete, update
281 // the parent job as well as the mailing status
282 if (!$anyChildLeft) {
283
284 $transaction = new CRM_Core_Transaction();
285
353ffa53
TO
286 $saveJob = new CRM_Mailing_DAO_MailingJob();
287 $saveJob->id = $job->id;
6a488035 288 $saveJob->end_date = date('YmdHis');
353ffa53 289 $saveJob->status = 'Complete';
6a488035
TO
290 $saveJob->save();
291
292 $mailing->reset();
293 $mailing->id = $job->mailing_id;
294 $mailing->is_completed = TRUE;
295 $mailing->save();
296 $transaction->commit();
b0fd9a5b
BS
297
298 // CRM-17763
c9a3cf8c 299 CRM_Utils_Hook::postMailing($job->mailing_id);
6a488035
TO
300 }
301 }
302 }
303
e0ef6999 304 /**
4f1f1f2a 305 * before we run jobs, we need to split the jobs
e0ef6999
EM
306 * @param int $offset
307 * @param null $mode
308 */
6a488035 309 public static function runJobs_pre($offset = 200, $mode = NULL) {
9da8dc8c 310 $job = new CRM_Mailing_BAO_MailingJob();
6a488035 311
353ffa53 312 $jobTable = CRM_Mailing_DAO_MailingJob::getTableName();
6a488035
TO
313 $mailingTable = CRM_Mailing_DAO_Mailing::getTableName();
314
315 $currentTime = date('YmdHis');
316 $mailingACL = CRM_Mailing_BAO_Mailing::mailingACL('m');
317
9da8dc8c 318 $workflowClause = CRM_Mailing_BAO_MailingJob::workflowClause();
6a488035
TO
319
320 $domainID = CRM_Core_Config::domainID();
321
322 $modeClause = 'AND m.sms_provider_id IS NULL';
323 if ($mode == 'sms') {
324 $modeClause = 'AND m.sms_provider_id IS NOT NULL';
325 }
326
327 // Select all the mailing jobs that are created from
328 // when the mailing is submitted or scheduled.
329 $query = "
330 SELECT j.*
331 FROM $jobTable j,
332 $mailingTable m
333 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
334 $workflowClause
335 $modeClause
336 AND j.is_test = 0
337 AND ( ( j.start_date IS null
338 AND j.scheduled_date <= $currentTime
339 AND j.status = 'Scheduled'
340 AND j.end_date IS null ) )
341 AND ((j.job_type is NULL) OR (j.job_type <> 'child'))
342 ORDER BY j.scheduled_date,
343 j.start_date";
344
6a488035
TO
345 $job->query($query);
346
6a488035
TO
347 // For each of the "Parent Jobs" we find, we split them into
348 // X Number of child jobs
349 while ($job->fetch()) {
350 // still use job level lock for each child job
83617886 351 $lock = Civi::lockManager()->acquire("data.mailing.job.{$job->id}");
6a488035
TO
352 if (!$lock->isAcquired()) {
353 continue;
354 }
355
356 // Re-fetch the job status in case things
357 // changed between the first query and now
358 // to avoid race conditions
6606b2e1 359 $job->status = CRM_Core_DAO::getFieldValue(
cbe30f5a 360 'CRM_Mailing_DAO_MailingJob',
6a488035 361 $job->id,
6606b2e1
DL
362 'status',
363 'id',
364 TRUE
6a488035
TO
365 );
366 if ($job->status != 'Scheduled') {
367 $lock->release();
368 continue;
369 }
370
2cf4876c
SL
371 $transaction = new CRM_Core_Transaction();
372
6a488035
TO
373 $job->split_job($offset);
374
f487e358 375 // Update the status of the parent job
376 self::create(['id' => $job->id, 'start_date' => date('YmdHis'), 'status' => 'Running']);
6a488035
TO
377 $transaction->commit();
378
379 // Release the job lock
380 $lock->release();
381 }
382 }
383
e0ef6999 384 /**
fe482240 385 * Split the parent job into n number of child job based on an offset.
4f1f1f2a 386 * If null or 0 , we create only one child job
e0ef6999
EM
387 * @param int $offset
388 */
6a488035
TO
389 public function split_job($offset = 200) {
390 $recipient_count = CRM_Mailing_BAO_Recipients::mailingSize($this->mailing_id);
391
9da8dc8c 392 $jobTable = CRM_Mailing_DAO_MailingJob::getTableName();
6a488035 393
6a488035
TO
394 $dao = new CRM_Core_DAO();
395
396 $sql = "
397INSERT INTO civicrm_mailing_job
398(`mailing_id`, `scheduled_date`, `status`, `job_type`, `parent_id`, `job_offset`, `job_limit`)
399VALUES (%1, %2, %3, %4, %5, %6, %7)
400";
be2fb01f
CW
401 $params = [
402 1 => [$this->mailing_id, 'Integer'],
403 2 => [$this->scheduled_date, 'String'],
404 3 => ['Scheduled', 'String'],
405 4 => ['child', 'String'],
406 5 => [$this->id, 'Integer'],
407 6 => [0, 'Integer'],
408 7 => [$recipient_count, 'Integer'],
409 ];
6a488035
TO
410
411 // create one child job if the mailing size is less than the offset
cbe30f5a 412 // probably use a CRM_Mailing_DAO_MailingJob( );
6a488035
TO
413 if (empty($offset) ||
414 $recipient_count <= $offset
415 ) {
416 CRM_Core_DAO::executeQuery($sql, $params);
417 }
418 else {
419 // Creating 'child jobs'
198c9339
RT
420 $scheduled_unixtime = strtotime($this->scheduled_date);
421 for ($i = 0, $s = 0; $i < $recipient_count; $i = $i + $offset, $s++) {
422 $params[2][0] = date('Y-m-d H:i:s', $scheduled_unixtime + $s);
6a488035
TO
423 $params[6][0] = $i;
424 $params[7][0] = $offset;
425 CRM_Core_DAO::executeQuery($sql, $params);
426 }
427 }
2cf4876c 428
6a488035
TO
429 }
430
e0ef6999 431 /**
100fef9d 432 * @param array $testParams
e0ef6999 433 */
6a488035
TO
434 public function queue($testParams = NULL) {
435 $mailing = new CRM_Mailing_BAO_Mailing();
436 $mailing->id = $this->mailing_id;
437 if (!empty($testParams)) {
438 $mailing->getTestRecipients($testParams);
439 }
440 else {
441 // We are still getting all the recipients from the parent job
442 // so we don't mess with the include/exclude logic.
443 $recipients = CRM_Mailing_BAO_Recipients::mailingQuery($this->mailing_id, $this->job_offset, $this->job_limit);
444
445 // FIXME: this is not very smart, we should move this to one DB call
446 // INSERT INTO ... SELECT FROM ..
447 // the thing we need to figure out is how to generate the hash automatically
353ffa53 448 $now = time();
be2fb01f 449 $params = [];
353ffa53 450 $count = 0;
6a488035 451 while ($recipients->fetch()) {
81f62fdb 452 // CRM-18543: there are situations when both the email and phone are null.
453 // Skip the recipient in this case.
454 if (empty($recipients->email_id) && empty($recipients->phone_id)) {
455 continue;
456 }
457
6a488035
TO
458 if ($recipients->phone_id) {
459 $recipients->email_id = "null";
460 }
461 else {
462 $recipients->phone_id = "null";
463 }
464
be2fb01f 465 $params[] = [
6a488035
TO
466 $this->id,
467 $recipients->email_id,
468 $recipients->contact_id,
469 $recipients->phone_id,
be2fb01f 470 ];
6a488035 471 $count++;
dfb542fc 472 if ($count % CRM_Mailing_Config::BULK_MAIL_INSERT_COUNT == 0) {
6a488035
TO
473 CRM_Mailing_Event_BAO_Queue::bulkCreate($params, $now);
474 $count = 0;
be2fb01f 475 $params = [];
6a488035
TO
476 }
477 }
478
479 if (!empty($params)) {
480 CRM_Mailing_Event_BAO_Queue::bulkCreate($params, $now);
481 }
482 }
483 }
484
485 /**
fe482240 486 * Send the mailing.
6a488035 487 *
7705c640
TO
488 * @deprecated
489 * This is used by CiviMail but will be made redundant by FlexMailer.
90c8230e
TO
490 * @param object $mailer
491 * A Mail object to send the messages.
2a6da8d7 492 *
100fef9d 493 * @param array $testParams
7705c640 494 * @return bool
6a488035
TO
495 */
496 public function deliver(&$mailer, $testParams = NULL) {
aa4343bc
TO
497 if (\Civi::settings()->get('experimentalFlexMailerEngine')) {
498 throw new \RuntimeException("Cannot use legacy deliver() when experimentalFlexMailerEngine is enabled");
499 }
500
6a488035
TO
501 $mailing = new CRM_Mailing_BAO_Mailing();
502 $mailing->id = $this->mailing_id;
503 $mailing->find(TRUE);
6a488035 504
97b7d4a0 505 $config = NULL;
6a488035
TO
506
507 if ($config == NULL) {
508 $config = CRM_Core_Config::singleton();
509 }
510
c59c5519 511 if (property_exists($mailing, 'language') && $mailing->language && $mailing->language != CRM_Core_I18n::getLocale()) {
a7c57397 512 $swapLang = CRM_Utils_AutoClean::swap('global://dbLocale?getter', 'call://i18n/setLocale', $mailing->language);
fd1f3a26
SV
513 }
514
6a488035 515 $job_date = CRM_Utils_Date::isoToMysql($this->scheduled_date);
be2fb01f 516 $fields = [];
6a488035
TO
517
518 if (!empty($testParams)) {
a5db8e6f 519 $mailing->subject = ts('[CiviMail Draft]') . ' ' . $mailing->subject;
6a488035
TO
520 }
521
522 CRM_Mailing_BAO_Mailing::tokenReplace($mailing);
523
524 // get and format attachments
525 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_mailing', $mailing->id);
526
527 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
528 CRM_Core_Smarty::registerStringResource();
529 }
530
df7f4ae1
DL
531 // CRM-12376
532 // This handles the edge case scenario where all the mails
25606795 533 // have been delivered in prior jobs.
df7f4ae1 534 $isDelivered = TRUE;
6a488035 535
dc00ac6d
TO
536 // make sure that there's no more than $mailerBatchLimit mails processed in a run
537 $mailerBatchLimit = Civi::settings()->get('mailerBatchLimit');
453c7bb8 538 $eq = self::findPendingTasks($this->id, $mailing->sms_provider_id ? 'sms' : 'email');
6a488035 539 while ($eq->fetch()) {
dc00ac6d 540 if ($mailerBatchLimit > 0 && self::$mailsProcessed >= $mailerBatchLimit) {
6a488035
TO
541 if (!empty($fields)) {
542 $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
543 }
6a488035
TO
544 return FALSE;
545 }
97b7d4a0 546 self::$mailsProcessed++;
6a488035 547
be2fb01f 548 $fields[] = [
6a488035
TO
549 'id' => $eq->id,
550 'hash' => $eq->hash,
551 'contact_id' => $eq->contact_id,
552 'email' => $eq->email,
553 'phone' => $eq->phone,
be2fb01f 554 ];
6a488035
TO
555 if (count($fields) == self::MAX_CONTACTS_TO_PROCESS) {
556 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
557 if (!$isDelivered) {
6a488035
TO
558 return $isDelivered;
559 }
be2fb01f 560 $fields = [];
6a488035
TO
561 }
562 }
563
6a488035
TO
564 if (!empty($fields)) {
565 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
566 }
567 return $isDelivered;
568 }
569
e0ef6999 570 /**
7705c640
TO
571 * @deprecated
572 * This is used by CiviMail but will be made redundant by FlexMailer.
519947b8
TO
573 * @param array $fields
574 * List of intended recipients.
575 * Each recipient is an array with keys 'hash', 'contact_id', 'email', etc.
e0ef6999
EM
576 * @param $mailing
577 * @param $mailer
578 * @param $job_date
579 * @param $attachments
580 *
581 * @return bool|null
582 * @throws Exception
583 */
6a488035
TO
584 public function deliverGroup(&$fields, &$mailing, &$mailer, &$job_date, &$attachments) {
585 static $smtpConnectionErrors = 0;
586
1a5727bd 587 if (!is_object($mailer) || empty($fields)) {
6a488035
TO
588 CRM_Core_Error::fatal();
589 }
590
591 // get the return properties
592 $returnProperties = $mailing->getReturnProperties();
be2fb01f 593 $params = $targetParams = $deliveredParams = [];
353ffa53 594 $count = 0;
e8654207 595 $retryGroup = FALSE;
7a9646c1 596
3d9b94a1
SB
597 // CRM-15702: Sending bulk sms to contacts without e-mail address fails.
598 // Solution is to skip checking for on hold
7e8c8317
SL
599 //do include a statement to check wether e-mail address is on hold
600 $skipOnHold = TRUE;
e36508bf 601 if ($mailing->sms_provider_id) {
7e8c8317
SL
602 //do not include a statement to check wether e-mail address is on hold
603 $skipOnHold = FALSE;
e36508bf 604 }
6a488035
TO
605
606 foreach ($fields as $key => $field) {
607 $params[] = $field['contact_id'];
608 }
609
610 $details = CRM_Utils_Token::getTokenDetails(
611 $params,
612 $returnProperties,
e36508bf 613 $skipOnHold, TRUE, NULL,
6a488035
TO
614 $mailing->getFlattenedTokens(),
615 get_class($this),
616 $this->id
617 );
618
619 $config = CRM_Core_Config::singleton();
620 foreach ($fields as $key => $field) {
621 $contactID = $field['contact_id'];
622 if (!array_key_exists($contactID, $details[0])) {
be2fb01f 623 $details[0][$contactID] = [];
6a488035 624 }
6a488035 625
25606795 626 // Compose the mailing.
6a488035
TO
627 $recipient = $replyToEmail = NULL;
628 $replyValue = strcmp($mailing->replyto_email, $mailing->from_email);
629 if ($replyValue) {
630 $replyToEmail = $mailing->replyto_email;
631 }
632
7eebf0c7 633 $message = $mailing->compose(
1a5727bd 634 $this->id, $field['id'], $field['hash'],
6a488035
TO
635 $field['contact_id'], $field['email'],
636 $recipient, FALSE, $details[0][$contactID], $attachments,
637 FALSE, NULL, $replyToEmail
638 );
639 if (empty($message)) {
640 // lets keep the message in the queue
641 // most likely a permissions related issue with smarty templates
642 // or a bad contact id? CRM-9833
643 continue;
644 }
645
25606795 646 // Send the mailing.
6a488035 647
ca807bbe
SL
648 $body = $message->get();
649 $headers = $message->headers();
6a488035
TO
650
651 if ($mailing->sms_provider_id) {
be2fb01f 652 $provider = CRM_SMS_Provider::singleton(['mailing_id' => $mailing->id]);
353ffa53
TO
653 $body = $provider->getMessage($message, $field['contact_id'], $details[0][$contactID]);
654 $headers = $provider->getRecipientDetails($field, $details[0][$contactID]);
6a488035
TO
655 }
656
657 // make $recipient actually be the *encoded* header, so as not to baffle Mail_RFC822, CRM-5743
658 $recipient = $headers['To'];
659 $result = NULL;
660
661 // disable error reporting on real mailings (but leave error reporting for tests), CRM-5744
662 if ($job_date) {
6a4257d4 663 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
6a488035
TO
664 }
665
666 $result = $mailer->send($recipient, $headers, $body, $this->id);
667
668 if ($job_date) {
6a4257d4 669 unset($errorScope);
6a488035
TO
670 }
671
c5a6413b 672 if (is_a($result, 'PEAR_Error') && !$mailing->sms_provider_id) {
6a488035
TO
673 // CRM-9191
674 $message = $result->getMessage();
206dc844 675 if ($this->isTemporaryError($message)) {
6a488035
TO
676 // lets log this message and code
677 $code = $result->getCode();
18810158 678 CRM_Core_Error::debug_log_message("SMTP Socket Error or failed to set sender error. Message: $message, Code: $code");
6a488035
TO
679
680 // these are socket write errors which most likely means smtp connection errors
e8654207 681 // lets skip them and reconnect.
6a488035
TO
682 $smtpConnectionErrors++;
683 if ($smtpConnectionErrors <= 5) {
e8654207 684 $mailer->disconnect();
685 $retryGroup = TRUE;
6a488035
TO
686 continue;
687 }
688
6a488035
TO
689 // seems like we have too many of them in a row, we should
690 // write stuff to disk and abort the cron job
2ede60ec
DL
691 $this->writeToDB(
692 $deliveredParams,
6a488035
TO
693 $targetParams,
694 $mailing,
695 $job_date
696 );
697
698 CRM_Core_Error::debug_log_message("Too many SMTP Socket Errors. Exiting");
699 CRM_Utils_System::civiExit();
700 }
701
25606795 702 // Register the bounce event.
6a488035 703
be2fb01f 704 $params = [
6a488035
TO
705 'event_queue_id' => $field['id'],
706 'job_id' => $this->id,
707 'hash' => $field['hash'],
be2fb01f 708 ];
6a488035
TO
709 $params = array_merge($params,
710 CRM_Mailing_BAO_BouncePattern::match($result->getMessage())
711 );
712 CRM_Mailing_Event_BAO_Bounce::create($params);
713 }
39373d13
JM
714 elseif (is_a($result, 'PEAR_Error') && $mailing->sms_provider_id) {
715 // Handle SMS errors: CRM-15426
716 $job_id = intval($this->id);
717 $mailing_id = intval($mailing->id);
718 CRM_Core_Error::debug_log_message("Failed to send SMS message. Vars: mailing_id: ${mailing_id}, job_id: ${job_id}. Error message follows.");
719 CRM_Core_Error::debug_log_message($result->getMessage());
720 }
6a488035 721 else {
25606795 722 // Register the delivery event.
6a488035
TO
723 $deliveredParams[] = $field['id'];
724 $targetParams[] = $field['contact_id'];
725
726 $count++;
dfb542fc 727 if ($count % CRM_Mailing_Config::BULK_MAIL_INSERT_COUNT == 0) {
2ede60ec
DL
728 $this->writeToDB(
729 $deliveredParams,
6a488035
TO
730 $targetParams,
731 $mailing,
732 $job_date
733 );
734 $count = 0;
735
736 // hack to stop mailing job at run time, CRM-4246.
737 // to avoid making too many DB calls for this rare case
738 // lets do it when we snapshot
1a5727bd 739 $status = CRM_Core_DAO::getFieldValue(
cbe30f5a 740 'CRM_Mailing_DAO_MailingJob',
6a488035 741 $this->id,
1a5727bd
DL
742 'status',
743 'id',
744 TRUE
6a488035 745 );
1a5727bd 746
6a488035
TO
747 if ($status != 'Running') {
748 return FALSE;
749 }
750 }
751 }
752
753 unset($result);
754
755 // seems like a successful delivery or bounce, lets decrement error count
756 // only if we have smtp connection errors
757 if ($smtpConnectionErrors > 0) {
758 $smtpConnectionErrors--;
759 }
760
761 // If we have enabled the Throttle option, this is the time to enforce it.
dc00ac6d
TO
762 $mailThrottleTime = Civi::settings()->get('mailThrottleTime');
763 if (!empty($mailThrottleTime)) {
764 usleep((int ) $mailThrottleTime);
6a488035
TO
765 }
766 }
767
2ede60ec
DL
768 $result = $this->writeToDB(
769 $deliveredParams,
6a488035
TO
770 $targetParams,
771 $mailing,
772 $job_date
773 );
774
e8654207 775 if ($retryGroup) {
776 return FALSE;
777 }
778
6a488035
TO
779 return $result;
780 }
781
206dc844 782 /**
783 * Determine if an SMTP error is temporary or permanent.
784 *
785 * @param string $message
786 * PEAR error message.
787 * @return bool
788 * TRUE - Temporary/retriable error
789 * FALSE - Permanent/non-retriable error
790 */
791 protected function isTemporaryError($message) {
792 // SMTP response code is buried in the message.
793 $code = preg_match('/ \(code: (.+), response: /', $message, $matches) ? $matches[1] : '';
794
795 if (strpos($message, 'Failed to write to socket') !== FALSE) {
796 return TRUE;
797 }
798
799 // Register 5xx SMTP response code (permanent failure) as bounce.
f1134501 800 if (isset($code{0}) && $code{0} === '5') {
206dc844 801 return FALSE;
802 }
803
804 if (strpos($message, 'Failed to set sender') !== FALSE) {
805 return TRUE;
806 }
807
808 if (strpos($message, 'Failed to add recipient') !== FALSE) {
809 return TRUE;
810 }
811
812 if (strpos($message, 'Failed to send data') !== FALSE) {
813 return TRUE;
814 }
815
816 return FALSE;
817 }
818
6a488035 819 /**
fe482240 820 * Cancel a mailing.
6a488035 821 *
90c8230e
TO
822 * @param int $mailingId
823 * The id of the mailing to be canceled.
6a488035
TO
824 */
825 public static function cancel($mailingId) {
826 $sql = "
827SELECT *
828FROM civicrm_mailing_job
829WHERE mailing_id = %1
830AND is_test = 0
831AND ( ( job_type IS NULL ) OR
832 job_type <> 'child' )
833";
be2fb01f 834 $params = [1 => [$mailingId, 'Integer']];
6a488035
TO
835 $job = CRM_Core_DAO::executeQuery($sql, $params);
836 if ($job->fetch() &&
be2fb01f 837 in_array($job->status, ['Scheduled', 'Running', 'Paused'])
6a488035
TO
838 ) {
839
f487e358 840 self::create(['id' => $job->id, 'end_date' => date('YmdHis'), 'status' => 'Canceled']);
6a488035
TO
841
842 // also cancel all child jobs
843 $sql = "
844UPDATE civicrm_mailing_job
845SET status = 'Canceled',
846 end_date = %2
847WHERE parent_id = %1
848AND is_test = 0
849AND job_type = 'child'
850AND status IN ( 'Scheduled', 'Running', 'Paused' )
851";
be2fb01f
CW
852 $params = [
853 1 => [$job->id, 'Integer'],
854 2 => [date('YmdHis'), 'Timestamp'],
855 ];
6a488035 856 CRM_Core_DAO::executeQuery($sql, $params);
6a488035
TO
857 }
858 }
859
4aa8f804
JP
860 /**
861 * Pause a mailing
67d4ed51
JP
862 *
863 * @param int $mailingID
864 * The id of the mailing to be paused.
4aa8f804
JP
865 */
866 public static function pause($mailingID) {
867 $sql = "
868 UPDATE civicrm_mailing_job
869 SET status = 'Paused'
870 WHERE mailing_id = %1
871 AND is_test = 0
872 AND status IN ('Scheduled', 'Running')
873 ";
be2fb01f 874 CRM_Core_DAO::executeQuery($sql, [1 => [$mailingID, 'Integer']]);
4aa8f804
JP
875 }
876
877 /**
878 * Resume a mailing
67d4ed51
JP
879 *
880 * @param int $mailingID
881 * The id of the mailing to be resumed.
4aa8f804
JP
882 */
883 public static function resume($mailingID) {
884 $sql = "
885 UPDATE civicrm_mailing_job
886 SET status = 'Scheduled'
887 WHERE mailing_id = %1
888 AND is_test = 0
889 AND start_date IS NULL
890 AND status = 'Paused'
891 ";
be2fb01f 892 CRM_Core_DAO::executeQuery($sql, [1 => [$mailingID, 'Integer']]);
4aa8f804
JP
893
894 $sql = "
895 UPDATE civicrm_mailing_job
896 SET status = 'Running'
897 WHERE mailing_id = %1
898 AND is_test = 0
899 AND start_date IS NOT NULL
900 AND status = 'Paused'
901 ";
be2fb01f 902 CRM_Core_DAO::executeQuery($sql, [1 => [$mailingID, 'Integer']]);
4aa8f804
JP
903 }
904
6a488035 905 /**
fe482240 906 * Return a translated status enum string.
6a488035 907 *
90c8230e
TO
908 * @param string $status
909 * The status enum.
6a488035 910 *
a6c01b45
CW
911 * @return string
912 * The translated version
6a488035
TO
913 */
914 public static function status($status) {
915 static $translation = NULL;
916
917 if (empty($translation)) {
be2fb01f 918 $translation = [
6a488035
TO
919 'Scheduled' => ts('Scheduled'),
920 'Running' => ts('Running'),
921 'Complete' => ts('Complete'),
922 'Paused' => ts('Paused'),
923 'Canceled' => ts('Canceled'),
be2fb01f 924 ];
6a488035
TO
925 }
926 return CRM_Utils_Array::value($status, $translation, ts('Not scheduled'));
927 }
928
929 /**
930 * Return a workflow clause for use in SQL queries,
931 * to only process jobs that are approved.
932 *
a6c01b45
CW
933 * @return string
934 * For use in a WHERE clause
6a488035
TO
935 */
936 public static function workflowClause() {
937 // add an additional check and only process
938 // jobs that are approved
939 if (CRM_Mailing_Info::workflowEnabled()) {
676159c9 940 $approveOptionID = CRM_Core_PseudoConstant::getKey('CRM_Mailing_BAO_Mailing', 'approval_status_id', 'Approved');
6a488035
TO
941 if ($approveOptionID) {
942 return " AND m.approval_status_id = $approveOptionID ";
943 }
944 }
945 return '';
946 }
947
e0ef6999 948 /**
100fef9d
CW
949 * @param array $deliveredParams
950 * @param array $targetParams
e0ef6999
EM
951 * @param $mailing
952 * @param $job_date
953 *
954 * @return bool
955 * @throws CRM_Core_Exception
956 * @throws Exception
957 */
2ede60ec
DL
958 public function writeToDB(
959 &$deliveredParams,
6a488035
TO
960 &$targetParams,
961 &$mailing,
962 $job_date
963 ) {
964 static $activityTypeID = NULL;
2ede60ec 965 static $writeActivity = NULL;
6a488035
TO
966
967 if (!empty($deliveredParams)) {
968 CRM_Mailing_Event_BAO_Delivered::bulkCreate($deliveredParams);
be2fb01f 969 $deliveredParams = [];
6a488035
TO
970 }
971
2ede60ec 972 if ($writeActivity === NULL) {
aaffa79f 973 $writeActivity = Civi::settings()->get('write_activity_record');
2ede60ec 974 }
6a488035 975
2ede60ec
DL
976 if (!$writeActivity) {
977 return TRUE;
978 }
979
980 $result = TRUE;
981 if (!empty($targetParams) && !empty($mailing->scheduled_id)) {
6a488035 982 if (!$activityTypeID) {
6a488035
TO
983 if ($mailing->sms_provider_id) {
984 $mailing->subject = $mailing->name;
a7321423 985 $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Mass SMS'
6a488035
TO
986 );
987 }
2ede60ec 988 else {
a7321423 989 $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Bulk Email');
2ede60ec 990 }
6a488035
TO
991 if (!$activityTypeID) {
992 CRM_Core_Error::fatal();
993 }
994 }
995
be2fb01f 996 $activity = [
6a488035
TO
997 'source_contact_id' => $mailing->scheduled_id,
998 // CRM-9519
999 'target_contact_id' => array_unique($targetParams),
6a488035
TO
1000 'activity_type_id' => $activityTypeID,
1001 'source_record_id' => $this->mailing_id,
1002 'activity_date_time' => $job_date,
1003 'subject' => $mailing->subject,
28106149 1004 'status_id' => 'Completed',
6a488035
TO
1005 'deleteActivityTarget' => FALSE,
1006 'campaign_id' => $mailing->campaign_id,
be2fb01f 1007 ];
6a488035
TO
1008
1009 //check whether activity is already created for this mailing.
1010 //if yes then create only target contact record.
1011 $query = "
1012SELECT id
1013FROM civicrm_activity
1014WHERE civicrm_activity.activity_type_id = %1
2ede60ec
DL
1015AND civicrm_activity.source_record_id = %2
1016";
6a488035 1017
be2fb01f
CW
1018 $queryParams = [
1019 1 => [$activityTypeID, 'Integer'],
1020 2 => [$this->mailing_id, 'Integer'],
1021 ];
2ede60ec 1022 $activityID = CRM_Core_DAO::singleValueQuery($query, $queryParams);
6a488035
TO
1023
1024 if ($activityID) {
1025 $activity['id'] = $activityID;
1026
1027 // CRM-9519
1028 if (CRM_Core_BAO_Email::isMultipleBulkMail()) {
b561230a
DL
1029 static $targetRecordID = NULL;
1030 if (!$targetRecordID) {
44f817d4 1031 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
b561230a
DL
1032 $targetRecordID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1033 }
1034
6a488035
TO
1035 // make sure we don't attempt to duplicate the target activity
1036 foreach ($activity['target_contact_id'] as $key => $targetID) {
b561230a
DL
1037 $sql = "
1038SELECT id
1039FROM civicrm_activity_contact
1040WHERE activity_id = $activityID
1041AND contact_id = $targetID
1042AND record_type_id = $targetRecordID
1043";
6a488035
TO
1044 if (CRM_Core_DAO::singleValueQuery($sql)) {
1045 unset($activity['target_contact_id'][$key]);
1046 }
1047 }
1048 }
1049 }
1050
28106149
PN
1051 try {
1052 civicrm_api3('Activity', 'create', $activity);
1053 }
1054 catch (Exception $e) {
6a488035
TO
1055 $result = FALSE;
1056 }
1057
be2fb01f 1058 $targetParams = [];
6a488035
TO
1059 }
1060
1061 return $result;
1062 }
96025800 1063
453c7bb8 1064 /**
5f9481d6
TO
1065 * Search the mailing-event queue for a list of pending delivery tasks.
1066 *
453c7bb8
TO
1067 * @param int $jobId
1068 * @param string $medium
1069 * Ex: 'email' or 'sms'.
5f9481d6 1070 *
453c7bb8
TO
1071 * @return \CRM_Mailing_Event_BAO_Queue
1072 * A query object whose rows provide ('id', 'contact_id', 'hash') and ('email' or 'phone').
1073 */
1074 public static function findPendingTasks($jobId, $medium) {
1075 $eq = new CRM_Mailing_Event_BAO_Queue();
1076 $queueTable = CRM_Mailing_Event_BAO_Queue::getTableName();
1077 $emailTable = CRM_Core_BAO_Email::getTableName();
5f9481d6 1078 $phoneTable = CRM_Core_BAO_Phone::getTableName();
453c7bb8
TO
1079 $contactTable = CRM_Contact_BAO_Contact::getTableName();
1080 $deliveredTable = CRM_Mailing_Event_BAO_Delivered::getTableName();
1081 $bounceTable = CRM_Mailing_Event_BAO_Bounce::getTableName();
1082
1083 $query = " SELECT $queueTable.id,
1084 $emailTable.email as email,
1085 $queueTable.contact_id,
1086 $queueTable.hash,
1087 NULL as phone
1088 FROM $queueTable
1089 INNER JOIN $emailTable
1090 ON $queueTable.email_id = $emailTable.id
1091 INNER JOIN $contactTable
1092 ON $contactTable.id = $emailTable.contact_id
1093 LEFT JOIN $deliveredTable
1094 ON $queueTable.id = $deliveredTable.event_queue_id
1095 LEFT JOIN $bounceTable
1096 ON $queueTable.id = $bounceTable.event_queue_id
1097 WHERE $queueTable.job_id = " . $jobId . "
1098 AND $deliveredTable.id IS null
1099 AND $bounceTable.id IS null
1100 AND $contactTable.is_opt_out = 0";
1101
1102 if ($medium === 'sms') {
1103 $query = "
1104 SELECT $queueTable.id,
1105 $phoneTable.phone as phone,
1106 $queueTable.contact_id,
1107 $queueTable.hash,
1108 NULL as email
1109 FROM $queueTable
1110 INNER JOIN $phoneTable
1111 ON $queueTable.phone_id = $phoneTable.id
1112 INNER JOIN $contactTable
1113 ON $contactTable.id = $phoneTable.contact_id
1114 LEFT JOIN $deliveredTable
1115 ON $queueTable.id = $deliveredTable.event_queue_id
1116 LEFT JOIN $bounceTable
1117 ON $queueTable.id = $bounceTable.event_queue_id
1118 WHERE $queueTable.job_id = " . $jobId . "
1119 AND $deliveredTable.id IS null
1120 AND $bounceTable.id IS null
1121 AND ( $contactTable.is_opt_out = 0
1122 OR $contactTable.do_not_sms = 0 )";
1123 }
1124 $eq->query($query);
1125 return $eq;
1126 }
1127
6f65a84f 1128 /**
1129 * Delete the mailing job.
1130 *
1131 * @param int $id
1132 * Mailing Job id.
1133 *
1134 * @return mixed
1135 */
1136 public static function del($id) {
1137 CRM_Utils_Hook::pre('delete', 'MailingJob', $id, CRM_Core_DAO::$_nullArray);
1138
1139 $jobDAO = new CRM_Mailing_BAO_MailingJob();
1140 $jobDAO->id = $id;
1141 $result = $jobDAO->delete();
1142
1143 CRM_Utils_Hook::post('delete', 'MailingJob', $jobDAO->id, $jobDAO);
1144
1145 return $result;
1146 }
1147
6a488035 1148}