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