(NFC) Update CRM/Friend CRM/Grant CRM/Group CRM/Mailing to be up to date to a future...
[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();
75 if (!empty($params['mailing_id'])) {
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);
504 $mailing->free();
505
97b7d4a0 506 $config = NULL;
6a488035
TO
507
508 if ($config == NULL) {
509 $config = CRM_Core_Config::singleton();
510 }
511
a7c57397
TO
512 if (property_exists($mailing, 'language') && $mailing->language && $mailing->language != 'en_US') {
513 $swapLang = CRM_Utils_AutoClean::swap('global://dbLocale?getter', 'call://i18n/setLocale', $mailing->language);
fd1f3a26
SV
514 }
515
6a488035 516 $job_date = CRM_Utils_Date::isoToMysql($this->scheduled_date);
be2fb01f 517 $fields = [];
6a488035
TO
518
519 if (!empty($testParams)) {
a5db8e6f 520 $mailing->subject = ts('[CiviMail Draft]') . ' ' . $mailing->subject;
6a488035
TO
521 }
522
523 CRM_Mailing_BAO_Mailing::tokenReplace($mailing);
524
525 // get and format attachments
526 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_mailing', $mailing->id);
527
528 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
529 CRM_Core_Smarty::registerStringResource();
530 }
531
df7f4ae1
DL
532 // CRM-12376
533 // This handles the edge case scenario where all the mails
25606795 534 // have been delivered in prior jobs.
df7f4ae1 535 $isDelivered = TRUE;
6a488035 536
dc00ac6d
TO
537 // make sure that there's no more than $mailerBatchLimit mails processed in a run
538 $mailerBatchLimit = Civi::settings()->get('mailerBatchLimit');
453c7bb8 539 $eq = self::findPendingTasks($this->id, $mailing->sms_provider_id ? 'sms' : 'email');
6a488035 540 while ($eq->fetch()) {
dc00ac6d 541 if ($mailerBatchLimit > 0 && self::$mailsProcessed >= $mailerBatchLimit) {
6a488035
TO
542 if (!empty($fields)) {
543 $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
544 }
545 $eq->free();
546 return FALSE;
547 }
97b7d4a0 548 self::$mailsProcessed++;
6a488035 549
be2fb01f 550 $fields[] = [
6a488035
TO
551 'id' => $eq->id,
552 'hash' => $eq->hash,
553 'contact_id' => $eq->contact_id,
554 'email' => $eq->email,
555 'phone' => $eq->phone,
be2fb01f 556 ];
6a488035
TO
557 if (count($fields) == self::MAX_CONTACTS_TO_PROCESS) {
558 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
559 if (!$isDelivered) {
560 $eq->free();
561 return $isDelivered;
562 }
be2fb01f 563 $fields = [];
6a488035
TO
564 }
565 }
566
567 $eq->free();
568
569 if (!empty($fields)) {
570 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
571 }
572 return $isDelivered;
573 }
574
e0ef6999 575 /**
7705c640
TO
576 * @deprecated
577 * This is used by CiviMail but will be made redundant by FlexMailer.
519947b8
TO
578 * @param array $fields
579 * List of intended recipients.
580 * Each recipient is an array with keys 'hash', 'contact_id', 'email', etc.
e0ef6999
EM
581 * @param $mailing
582 * @param $mailer
583 * @param $job_date
584 * @param $attachments
585 *
586 * @return bool|null
587 * @throws Exception
588 */
6a488035
TO
589 public function deliverGroup(&$fields, &$mailing, &$mailer, &$job_date, &$attachments) {
590 static $smtpConnectionErrors = 0;
591
1a5727bd 592 if (!is_object($mailer) || empty($fields)) {
6a488035
TO
593 CRM_Core_Error::fatal();
594 }
595
596 // get the return properties
597 $returnProperties = $mailing->getReturnProperties();
be2fb01f 598 $params = $targetParams = $deliveredParams = [];
353ffa53 599 $count = 0;
e8654207 600 $retryGroup = FALSE;
7a9646c1 601
3d9b94a1
SB
602 // CRM-15702: Sending bulk sms to contacts without e-mail address fails.
603 // Solution is to skip checking for on hold
7e8c8317
SL
604 //do include a statement to check wether e-mail address is on hold
605 $skipOnHold = TRUE;
e36508bf 606 if ($mailing->sms_provider_id) {
7e8c8317
SL
607 //do not include a statement to check wether e-mail address is on hold
608 $skipOnHold = FALSE;
e36508bf 609 }
6a488035
TO
610
611 foreach ($fields as $key => $field) {
612 $params[] = $field['contact_id'];
613 }
614
615 $details = CRM_Utils_Token::getTokenDetails(
616 $params,
617 $returnProperties,
e36508bf 618 $skipOnHold, TRUE, NULL,
6a488035
TO
619 $mailing->getFlattenedTokens(),
620 get_class($this),
621 $this->id
622 );
623
624 $config = CRM_Core_Config::singleton();
625 foreach ($fields as $key => $field) {
626 $contactID = $field['contact_id'];
627 if (!array_key_exists($contactID, $details[0])) {
be2fb01f 628 $details[0][$contactID] = [];
6a488035 629 }
6a488035 630
25606795 631 // Compose the mailing.
6a488035
TO
632 $recipient = $replyToEmail = NULL;
633 $replyValue = strcmp($mailing->replyto_email, $mailing->from_email);
634 if ($replyValue) {
635 $replyToEmail = $mailing->replyto_email;
636 }
637
7eebf0c7 638 $message = $mailing->compose(
1a5727bd 639 $this->id, $field['id'], $field['hash'],
6a488035
TO
640 $field['contact_id'], $field['email'],
641 $recipient, FALSE, $details[0][$contactID], $attachments,
642 FALSE, NULL, $replyToEmail
643 );
644 if (empty($message)) {
645 // lets keep the message in the queue
646 // most likely a permissions related issue with smarty templates
647 // or a bad contact id? CRM-9833
648 continue;
649 }
650
25606795 651 // Send the mailing.
6a488035 652
ca807bbe
SL
653 $body = $message->get();
654 $headers = $message->headers();
6a488035
TO
655
656 if ($mailing->sms_provider_id) {
be2fb01f 657 $provider = CRM_SMS_Provider::singleton(['mailing_id' => $mailing->id]);
353ffa53
TO
658 $body = $provider->getMessage($message, $field['contact_id'], $details[0][$contactID]);
659 $headers = $provider->getRecipientDetails($field, $details[0][$contactID]);
6a488035
TO
660 }
661
662 // make $recipient actually be the *encoded* header, so as not to baffle Mail_RFC822, CRM-5743
663 $recipient = $headers['To'];
664 $result = NULL;
665
666 // disable error reporting on real mailings (but leave error reporting for tests), CRM-5744
667 if ($job_date) {
6a4257d4 668 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
6a488035
TO
669 }
670
671 $result = $mailer->send($recipient, $headers, $body, $this->id);
672
673 if ($job_date) {
6a4257d4 674 unset($errorScope);
6a488035
TO
675 }
676
c5a6413b 677 if (is_a($result, 'PEAR_Error') && !$mailing->sms_provider_id) {
6a488035
TO
678 // CRM-9191
679 $message = $result->getMessage();
206dc844 680 if ($this->isTemporaryError($message)) {
6a488035
TO
681 // lets log this message and code
682 $code = $result->getCode();
18810158 683 CRM_Core_Error::debug_log_message("SMTP Socket Error or failed to set sender error. Message: $message, Code: $code");
6a488035
TO
684
685 // these are socket write errors which most likely means smtp connection errors
e8654207 686 // lets skip them and reconnect.
6a488035
TO
687 $smtpConnectionErrors++;
688 if ($smtpConnectionErrors <= 5) {
e8654207 689 $mailer->disconnect();
690 $retryGroup = TRUE;
6a488035
TO
691 continue;
692 }
693
6a488035
TO
694 // seems like we have too many of them in a row, we should
695 // write stuff to disk and abort the cron job
2ede60ec
DL
696 $this->writeToDB(
697 $deliveredParams,
6a488035
TO
698 $targetParams,
699 $mailing,
700 $job_date
701 );
702
703 CRM_Core_Error::debug_log_message("Too many SMTP Socket Errors. Exiting");
704 CRM_Utils_System::civiExit();
705 }
706
25606795 707 // Register the bounce event.
6a488035 708
be2fb01f 709 $params = [
6a488035
TO
710 'event_queue_id' => $field['id'],
711 'job_id' => $this->id,
712 'hash' => $field['hash'],
be2fb01f 713 ];
6a488035
TO
714 $params = array_merge($params,
715 CRM_Mailing_BAO_BouncePattern::match($result->getMessage())
716 );
717 CRM_Mailing_Event_BAO_Bounce::create($params);
718 }
39373d13
JM
719 elseif (is_a($result, 'PEAR_Error') && $mailing->sms_provider_id) {
720 // Handle SMS errors: CRM-15426
721 $job_id = intval($this->id);
722 $mailing_id = intval($mailing->id);
723 CRM_Core_Error::debug_log_message("Failed to send SMS message. Vars: mailing_id: ${mailing_id}, job_id: ${job_id}. Error message follows.");
724 CRM_Core_Error::debug_log_message($result->getMessage());
725 }
6a488035 726 else {
25606795 727 // Register the delivery event.
6a488035
TO
728 $deliveredParams[] = $field['id'];
729 $targetParams[] = $field['contact_id'];
730
731 $count++;
dfb542fc 732 if ($count % CRM_Mailing_Config::BULK_MAIL_INSERT_COUNT == 0) {
2ede60ec
DL
733 $this->writeToDB(
734 $deliveredParams,
6a488035
TO
735 $targetParams,
736 $mailing,
737 $job_date
738 );
739 $count = 0;
740
741 // hack to stop mailing job at run time, CRM-4246.
742 // to avoid making too many DB calls for this rare case
743 // lets do it when we snapshot
1a5727bd 744 $status = CRM_Core_DAO::getFieldValue(
cbe30f5a 745 'CRM_Mailing_DAO_MailingJob',
6a488035 746 $this->id,
1a5727bd
DL
747 'status',
748 'id',
749 TRUE
6a488035 750 );
1a5727bd 751
6a488035
TO
752 if ($status != 'Running') {
753 return FALSE;
754 }
755 }
756 }
757
758 unset($result);
759
760 // seems like a successful delivery or bounce, lets decrement error count
761 // only if we have smtp connection errors
762 if ($smtpConnectionErrors > 0) {
763 $smtpConnectionErrors--;
764 }
765
766 // If we have enabled the Throttle option, this is the time to enforce it.
dc00ac6d
TO
767 $mailThrottleTime = Civi::settings()->get('mailThrottleTime');
768 if (!empty($mailThrottleTime)) {
769 usleep((int ) $mailThrottleTime);
6a488035
TO
770 }
771 }
772
2ede60ec
DL
773 $result = $this->writeToDB(
774 $deliveredParams,
6a488035
TO
775 $targetParams,
776 $mailing,
777 $job_date
778 );
779
e8654207 780 if ($retryGroup) {
781 return FALSE;
782 }
783
6a488035
TO
784 return $result;
785 }
786
206dc844 787 /**
788 * Determine if an SMTP error is temporary or permanent.
789 *
790 * @param string $message
791 * PEAR error message.
792 * @return bool
793 * TRUE - Temporary/retriable error
794 * FALSE - Permanent/non-retriable error
795 */
796 protected function isTemporaryError($message) {
797 // SMTP response code is buried in the message.
798 $code = preg_match('/ \(code: (.+), response: /', $message, $matches) ? $matches[1] : '';
799
800 if (strpos($message, 'Failed to write to socket') !== FALSE) {
801 return TRUE;
802 }
803
804 // Register 5xx SMTP response code (permanent failure) as bounce.
f1134501 805 if (isset($code{0}) && $code{0} === '5') {
206dc844 806 return FALSE;
807 }
808
809 if (strpos($message, 'Failed to set sender') !== FALSE) {
810 return TRUE;
811 }
812
813 if (strpos($message, 'Failed to add recipient') !== FALSE) {
814 return TRUE;
815 }
816
817 if (strpos($message, 'Failed to send data') !== FALSE) {
818 return TRUE;
819 }
820
821 return FALSE;
822 }
823
6a488035 824 /**
fe482240 825 * Cancel a mailing.
6a488035 826 *
90c8230e
TO
827 * @param int $mailingId
828 * The id of the mailing to be canceled.
6a488035
TO
829 */
830 public static function cancel($mailingId) {
831 $sql = "
832SELECT *
833FROM civicrm_mailing_job
834WHERE mailing_id = %1
835AND is_test = 0
836AND ( ( job_type IS NULL ) OR
837 job_type <> 'child' )
838";
be2fb01f 839 $params = [1 => [$mailingId, 'Integer']];
6a488035
TO
840 $job = CRM_Core_DAO::executeQuery($sql, $params);
841 if ($job->fetch() &&
be2fb01f 842 in_array($job->status, ['Scheduled', 'Running', 'Paused'])
6a488035
TO
843 ) {
844
f487e358 845 self::create(['id' => $job->id, 'end_date' => date('YmdHis'), 'status' => 'Canceled']);
6a488035
TO
846
847 // also cancel all child jobs
848 $sql = "
849UPDATE civicrm_mailing_job
850SET status = 'Canceled',
851 end_date = %2
852WHERE parent_id = %1
853AND is_test = 0
854AND job_type = 'child'
855AND status IN ( 'Scheduled', 'Running', 'Paused' )
856";
be2fb01f
CW
857 $params = [
858 1 => [$job->id, 'Integer'],
859 2 => [date('YmdHis'), 'Timestamp'],
860 ];
6a488035 861 CRM_Core_DAO::executeQuery($sql, $params);
6a488035
TO
862 }
863 }
864
4aa8f804
JP
865 /**
866 * Pause a mailing
67d4ed51
JP
867 *
868 * @param int $mailingID
869 * The id of the mailing to be paused.
4aa8f804
JP
870 */
871 public static function pause($mailingID) {
872 $sql = "
873 UPDATE civicrm_mailing_job
874 SET status = 'Paused'
875 WHERE mailing_id = %1
876 AND is_test = 0
877 AND status IN ('Scheduled', 'Running')
878 ";
be2fb01f 879 CRM_Core_DAO::executeQuery($sql, [1 => [$mailingID, 'Integer']]);
4aa8f804
JP
880 }
881
882 /**
883 * Resume a mailing
67d4ed51
JP
884 *
885 * @param int $mailingID
886 * The id of the mailing to be resumed.
4aa8f804
JP
887 */
888 public static function resume($mailingID) {
889 $sql = "
890 UPDATE civicrm_mailing_job
891 SET status = 'Scheduled'
892 WHERE mailing_id = %1
893 AND is_test = 0
894 AND start_date IS NULL
895 AND status = 'Paused'
896 ";
be2fb01f 897 CRM_Core_DAO::executeQuery($sql, [1 => [$mailingID, 'Integer']]);
4aa8f804
JP
898
899 $sql = "
900 UPDATE civicrm_mailing_job
901 SET status = 'Running'
902 WHERE mailing_id = %1
903 AND is_test = 0
904 AND start_date IS NOT NULL
905 AND status = 'Paused'
906 ";
be2fb01f 907 CRM_Core_DAO::executeQuery($sql, [1 => [$mailingID, 'Integer']]);
4aa8f804
JP
908 }
909
6a488035 910 /**
fe482240 911 * Return a translated status enum string.
6a488035 912 *
90c8230e
TO
913 * @param string $status
914 * The status enum.
6a488035 915 *
a6c01b45
CW
916 * @return string
917 * The translated version
6a488035
TO
918 */
919 public static function status($status) {
920 static $translation = NULL;
921
922 if (empty($translation)) {
be2fb01f 923 $translation = [
6a488035
TO
924 'Scheduled' => ts('Scheduled'),
925 'Running' => ts('Running'),
926 'Complete' => ts('Complete'),
927 'Paused' => ts('Paused'),
928 'Canceled' => ts('Canceled'),
be2fb01f 929 ];
6a488035
TO
930 }
931 return CRM_Utils_Array::value($status, $translation, ts('Not scheduled'));
932 }
933
934 /**
935 * Return a workflow clause for use in SQL queries,
936 * to only process jobs that are approved.
937 *
a6c01b45
CW
938 * @return string
939 * For use in a WHERE clause
6a488035
TO
940 */
941 public static function workflowClause() {
942 // add an additional check and only process
943 // jobs that are approved
944 if (CRM_Mailing_Info::workflowEnabled()) {
676159c9 945 $approveOptionID = CRM_Core_PseudoConstant::getKey('CRM_Mailing_BAO_Mailing', 'approval_status_id', 'Approved');
6a488035
TO
946 if ($approveOptionID) {
947 return " AND m.approval_status_id = $approveOptionID ";
948 }
949 }
950 return '';
951 }
952
e0ef6999 953 /**
100fef9d
CW
954 * @param array $deliveredParams
955 * @param array $targetParams
e0ef6999
EM
956 * @param $mailing
957 * @param $job_date
958 *
959 * @return bool
960 * @throws CRM_Core_Exception
961 * @throws Exception
962 */
2ede60ec
DL
963 public function writeToDB(
964 &$deliveredParams,
6a488035
TO
965 &$targetParams,
966 &$mailing,
967 $job_date
968 ) {
969 static $activityTypeID = NULL;
2ede60ec 970 static $writeActivity = NULL;
6a488035
TO
971
972 if (!empty($deliveredParams)) {
973 CRM_Mailing_Event_BAO_Delivered::bulkCreate($deliveredParams);
be2fb01f 974 $deliveredParams = [];
6a488035
TO
975 }
976
2ede60ec 977 if ($writeActivity === NULL) {
aaffa79f 978 $writeActivity = Civi::settings()->get('write_activity_record');
2ede60ec 979 }
6a488035 980
2ede60ec
DL
981 if (!$writeActivity) {
982 return TRUE;
983 }
984
985 $result = TRUE;
986 if (!empty($targetParams) && !empty($mailing->scheduled_id)) {
6a488035 987 if (!$activityTypeID) {
6a488035
TO
988 if ($mailing->sms_provider_id) {
989 $mailing->subject = $mailing->name;
a7321423 990 $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Mass SMS'
6a488035
TO
991 );
992 }
2ede60ec 993 else {
a7321423 994 $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Bulk Email');
2ede60ec 995 }
6a488035
TO
996 if (!$activityTypeID) {
997 CRM_Core_Error::fatal();
998 }
999 }
1000
be2fb01f 1001 $activity = [
6a488035
TO
1002 'source_contact_id' => $mailing->scheduled_id,
1003 // CRM-9519
1004 'target_contact_id' => array_unique($targetParams),
6a488035
TO
1005 'activity_type_id' => $activityTypeID,
1006 'source_record_id' => $this->mailing_id,
1007 'activity_date_time' => $job_date,
1008 'subject' => $mailing->subject,
1009 'status_id' => 2,
1010 'deleteActivityTarget' => FALSE,
1011 'campaign_id' => $mailing->campaign_id,
be2fb01f 1012 ];
6a488035
TO
1013
1014 //check whether activity is already created for this mailing.
1015 //if yes then create only target contact record.
1016 $query = "
1017SELECT id
1018FROM civicrm_activity
1019WHERE civicrm_activity.activity_type_id = %1
2ede60ec
DL
1020AND civicrm_activity.source_record_id = %2
1021";
6a488035 1022
be2fb01f
CW
1023 $queryParams = [
1024 1 => [$activityTypeID, 'Integer'],
1025 2 => [$this->mailing_id, 'Integer'],
1026 ];
2ede60ec 1027 $activityID = CRM_Core_DAO::singleValueQuery($query, $queryParams);
6a488035
TO
1028
1029 if ($activityID) {
1030 $activity['id'] = $activityID;
1031
1032 // CRM-9519
1033 if (CRM_Core_BAO_Email::isMultipleBulkMail()) {
b561230a
DL
1034 static $targetRecordID = NULL;
1035 if (!$targetRecordID) {
44f817d4 1036 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
b561230a
DL
1037 $targetRecordID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1038 }
1039
6a488035
TO
1040 // make sure we don't attempt to duplicate the target activity
1041 foreach ($activity['target_contact_id'] as $key => $targetID) {
b561230a
DL
1042 $sql = "
1043SELECT id
1044FROM civicrm_activity_contact
1045WHERE activity_id = $activityID
1046AND contact_id = $targetID
1047AND record_type_id = $targetRecordID
1048";
6a488035
TO
1049 if (CRM_Core_DAO::singleValueQuery($sql)) {
1050 unset($activity['target_contact_id'][$key]);
1051 }
1052 }
1053 }
1054 }
1055
2ede60ec 1056 if (is_a(CRM_Activity_BAO_Activity::create($activity), 'CRM_Core_Error')) {
6a488035
TO
1057 $result = FALSE;
1058 }
1059
be2fb01f 1060 $targetParams = [];
6a488035
TO
1061 }
1062
1063 return $result;
1064 }
96025800 1065
453c7bb8 1066 /**
5f9481d6
TO
1067 * Search the mailing-event queue for a list of pending delivery tasks.
1068 *
453c7bb8
TO
1069 * @param int $jobId
1070 * @param string $medium
1071 * Ex: 'email' or 'sms'.
5f9481d6 1072 *
453c7bb8
TO
1073 * @return \CRM_Mailing_Event_BAO_Queue
1074 * A query object whose rows provide ('id', 'contact_id', 'hash') and ('email' or 'phone').
1075 */
1076 public static function findPendingTasks($jobId, $medium) {
1077 $eq = new CRM_Mailing_Event_BAO_Queue();
1078 $queueTable = CRM_Mailing_Event_BAO_Queue::getTableName();
1079 $emailTable = CRM_Core_BAO_Email::getTableName();
5f9481d6 1080 $phoneTable = CRM_Core_BAO_Phone::getTableName();
453c7bb8
TO
1081 $contactTable = CRM_Contact_BAO_Contact::getTableName();
1082 $deliveredTable = CRM_Mailing_Event_BAO_Delivered::getTableName();
1083 $bounceTable = CRM_Mailing_Event_BAO_Bounce::getTableName();
1084
1085 $query = " SELECT $queueTable.id,
1086 $emailTable.email as email,
1087 $queueTable.contact_id,
1088 $queueTable.hash,
1089 NULL as phone
1090 FROM $queueTable
1091 INNER JOIN $emailTable
1092 ON $queueTable.email_id = $emailTable.id
1093 INNER JOIN $contactTable
1094 ON $contactTable.id = $emailTable.contact_id
1095 LEFT JOIN $deliveredTable
1096 ON $queueTable.id = $deliveredTable.event_queue_id
1097 LEFT JOIN $bounceTable
1098 ON $queueTable.id = $bounceTable.event_queue_id
1099 WHERE $queueTable.job_id = " . $jobId . "
1100 AND $deliveredTable.id IS null
1101 AND $bounceTable.id IS null
1102 AND $contactTable.is_opt_out = 0";
1103
1104 if ($medium === 'sms') {
1105 $query = "
1106 SELECT $queueTable.id,
1107 $phoneTable.phone as phone,
1108 $queueTable.contact_id,
1109 $queueTable.hash,
1110 NULL as email
1111 FROM $queueTable
1112 INNER JOIN $phoneTable
1113 ON $queueTable.phone_id = $phoneTable.id
1114 INNER JOIN $contactTable
1115 ON $contactTable.id = $phoneTable.contact_id
1116 LEFT JOIN $deliveredTable
1117 ON $queueTable.id = $deliveredTable.event_queue_id
1118 LEFT JOIN $bounceTable
1119 ON $queueTable.id = $bounceTable.event_queue_id
1120 WHERE $queueTable.job_id = " . $jobId . "
1121 AND $deliveredTable.id IS null
1122 AND $bounceTable.id IS null
1123 AND ( $contactTable.is_opt_out = 0
1124 OR $contactTable.do_not_sms = 0 )";
1125 }
1126 $eq->query($query);
1127 return $eq;
1128 }
1129
6f65a84f 1130 /**
1131 * Delete the mailing job.
1132 *
1133 * @param int $id
1134 * Mailing Job id.
1135 *
1136 * @return mixed
1137 */
1138 public static function del($id) {
1139 CRM_Utils_Hook::pre('delete', 'MailingJob', $id, CRM_Core_DAO::$_nullArray);
1140
1141 $jobDAO = new CRM_Mailing_BAO_MailingJob();
1142 $jobDAO->id = $id;
1143 $result = $jobDAO->delete();
1144
1145 CRM_Utils_Hook::post('delete', 'MailingJob', $jobDAO->id, $jobDAO);
1146
1147 return $result;
1148 }
1149
6a488035 1150}