3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
34 require_once 'Mail.php';
37 * Class CRM_Mailing_BAO_MailingJob
39 class CRM_Mailing_BAO_MailingJob
extends CRM_Mailing_DAO_MailingJob
{
40 const MAX_CONTACTS_TO_PROCESS
= 1000;
43 * (Dear God Why) Keep a global count of mails processed within the current
48 public static $mailsProcessed = 0;
53 public function __construct() {
54 parent
::__construct();
60 * @param array $params
62 * @return \CRM_Mailing_BAO_MailingJob
63 * @throws \CRM_Core_Exception
65 public static function create($params) {
66 if (empty($params['id']) && empty($params['mailing_id'])) {
67 throw new CRM_Core_Exception("Failed to create job: Unknown mailing ID");
69 $op = empty($params['id']) ?
'create' : 'edit';
70 CRM_Utils_Hook
::pre($op, 'MailingJob', CRM_Utils_Array
::value('id', $params), $params);
72 $jobDAO = new CRM_Mailing_BAO_MailingJob();
73 $jobDAO->copyValues($params, TRUE);
75 if (!empty($params['mailing_id']) && empty('is_calling_function_updated_to_reflect_deprecation')) {
76 CRM_Mailing_BAO_Mailing
::getRecipients($params['mailing_id']);
78 CRM_Utils_Hook
::post($op, 'MailingJob', $jobDAO->id
, $jobDAO);
83 * Initiate all pending/ready jobs.
85 * @param array $testParams
90 public static function runJobs($testParams = NULL, $mode = NULL) {
91 $job = new CRM_Mailing_BAO_MailingJob();
93 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
94 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
95 $mailerBatchLimit = Civi
::settings()->get('mailerBatchLimit');
97 if (!empty($testParams)) {
101 WHERE id = {$testParams['job_id']}";
105 $currentTime = date('YmdHis');
106 $mailingACL = CRM_Mailing_BAO_Mailing
::mailingACL('m');
107 $domainID = CRM_Core_Config
::domainID();
109 $modeClause = 'AND m.sms_provider_id IS NULL';
110 if ($mode == 'sms') {
111 $modeClause = 'AND m.sms_provider_id IS NOT NULL';
114 // Select the first child job that is scheduled
120 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
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')
130 ORDER BY j.scheduled_date ASC,
137 while ($job->fetch()) {
138 // still use job level lock for each child job
139 $lock = Civi
::lockManager()->acquire("data.mailing.job.{$job->id}");
140 if (!$lock->isAcquired()) {
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
149 $job->status
= CRM_Core_DAO
::getFieldValue(
150 'CRM_Mailing_DAO_MailingJob',
158 $job->status
!= 'Running' &&
159 $job->status
!= 'Scheduled'
161 // this includes Cancelled and other statuses, CRM-4246
167 /* Queue up recipients for the child job being launched */
169 if ($job->status
!= 'Running') {
170 $transaction = new CRM_Core_Transaction();
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);
176 // Update to show job has started.
179 'start_date' => date('YmdHis'),
180 'status' => 'Running',
183 $transaction->commit();
187 if ($mode === NULL) {
188 $mailer = \Civi
::service('pear_mail');
190 elseif ($mode == 'sms') {
191 $mailer = CRM_SMS_Provider
::singleton(['mailing_id' => $job->mailing_id
]);
194 // Compose and deliver each child job
195 if (\CRM_Utils_Constant
::value('CIVICRM_FLEXMAILER_HACK_DELIVER')) {
196 $isComplete = Civi\Core\Resolver
::singleton()->call(CIVICRM_FLEXMAILER_HACK_DELIVER
, [$job, $mailer, $testParams]);
199 $isComplete = $job->deliver($mailer, $testParams);
202 CRM_Utils_Hook
::post('create', 'CRM_Mailing_DAO_Spool', $job->id
, $isComplete);
204 // Mark the child complete
208 $transaction = new CRM_Core_Transaction();
209 self
::create(['id' => $job->id
, 'end_date' => date('YmdHis'), 'status' => 'Complete']);
210 $transaction->commit();
212 // don't mark the mailing as complete
215 // Release the child joblock
222 // CRM-17629: Stop processing jobs if mailer batch limit reached
223 if ($mailerBatchLimit > 0 && self
::$mailsProcessed >= $mailerBatchLimit) {
231 * Post process to determine if the parent job
232 * as well as the mailing is complete after the run.
235 public static function runJobs_post($mode = NULL) {
237 $job = new CRM_Mailing_BAO_MailingJob();
239 $mailing = new CRM_Mailing_BAO_Mailing();
241 $config = CRM_Core_Config
::singleton();
242 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
243 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
245 $currentTime = date('YmdHis');
246 $mailingACL = CRM_Mailing_BAO_Mailing
::mailingACL('m');
247 $domainID = CRM_Core_Config
::domainID();
253 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
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,
264 // For each parent job that is running, let's look at their child jobs
265 while ($job->fetch()) {
267 $child_job = new CRM_Mailing_BAO_MailingJob();
271 FROM civicrm_mailing_job j, civicrm_mailing m
272 WHERE m.id = j.mailing_id
273 AND j.job_type = 'child'
275 AND j.status <> 'Complete'";
276 $params = [1 => [$job->id
, 'Integer']];
278 $anyChildLeft = CRM_Core_DAO
::singleValueQuery($child_job_sql, $params);
280 // all of the child jobs are complete, update
281 // the parent job as well as the mailing status
282 if (!$anyChildLeft) {
284 $transaction = new CRM_Core_Transaction();
286 $saveJob = new CRM_Mailing_DAO_MailingJob();
287 $saveJob->id
= $job->id
;
288 $saveJob->end_date
= date('YmdHis');
289 $saveJob->status
= 'Complete';
293 $mailing->id
= $job->mailing_id
;
294 $mailing->is_completed
= TRUE;
296 $transaction->commit();
299 CRM_Utils_Hook
::postMailing($job->mailing_id
);
305 * before we run jobs, we need to split the jobs
309 public static function runJobs_pre($offset = 200, $mode = NULL) {
310 $job = new CRM_Mailing_BAO_MailingJob();
312 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
313 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
315 $currentTime = date('YmdHis');
316 $mailingACL = CRM_Mailing_BAO_Mailing
::mailingACL('m');
318 $workflowClause = CRM_Mailing_BAO_MailingJob
::workflowClause();
320 $domainID = CRM_Core_Config
::domainID();
322 $modeClause = 'AND m.sms_provider_id IS NULL';
323 if ($mode == 'sms') {
324 $modeClause = 'AND m.sms_provider_id IS NOT NULL';
327 // Select all the mailing jobs that are created from
328 // when the mailing is submitted or scheduled.
333 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
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,
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
351 $lock = Civi
::lockManager()->acquire("data.mailing.job.{$job->id}");
352 if (!$lock->isAcquired()) {
356 // Re-fetch the job status in case things
357 // changed between the first query and now
358 // to avoid race conditions
359 $job->status
= CRM_Core_DAO
::getFieldValue(
360 'CRM_Mailing_DAO_MailingJob',
366 if ($job->status
!= 'Scheduled') {
371 $transaction = new CRM_Core_Transaction();
373 $job->split_job($offset);
375 // Update the status of the parent job
376 self
::create(['id' => $job->id
, 'start_date' => date('YmdHis'), 'status' => 'Running']);
377 $transaction->commit();
379 // Release the job lock
385 * Split the parent job into n number of child job based on an offset.
386 * If null or 0 , we create only one child job
389 public function split_job($offset = 200) {
390 $recipient_count = CRM_Mailing_BAO_Recipients
::mailingSize($this->mailing_id
);
392 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
394 $dao = new CRM_Core_DAO();
397 INSERT INTO civicrm_mailing_job
398 (`mailing_id`, `scheduled_date`, `status`, `job_type`, `parent_id`, `job_offset`, `job_limit`)
399 VALUES (%1, %2, %3, %4, %5, %6, %7)
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'],
408 7 => [$recipient_count, 'Integer'],
411 // create one child job if the mailing size is less than the offset
412 // probably use a CRM_Mailing_DAO_MailingJob( );
413 if (empty($offset) ||
414 $recipient_count <= $offset
416 CRM_Core_DAO
::executeQuery($sql, $params);
419 // Creating 'child jobs'
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);
424 $params[7][0] = $offset;
425 CRM_Core_DAO
::executeQuery($sql, $params);
432 * @param array $testParams
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);
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
);
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
451 while ($recipients->fetch()) {
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
)) {
458 if ($recipients->phone_id
) {
459 $recipients->email_id
= "null";
462 $recipients->phone_id
= "null";
467 $recipients->email_id
,
468 $recipients->contact_id
,
469 $recipients->phone_id
,
472 if ($count % CRM_Mailing_Config
::BULK_MAIL_INSERT_COUNT
== 0) {
473 CRM_Mailing_Event_BAO_Queue
::bulkCreate($params, $now);
479 if (!empty($params)) {
480 CRM_Mailing_Event_BAO_Queue
::bulkCreate($params, $now);
489 * This is used by CiviMail but will be made redundant by FlexMailer.
490 * @param object $mailer
491 * A Mail object to send the messages.
493 * @param array $testParams
496 public function deliver(&$mailer, $testParams = NULL) {
497 if (\Civi
::settings()->get('experimentalFlexMailerEngine')) {
498 throw new \
RuntimeException("Cannot use legacy deliver() when experimentalFlexMailerEngine is enabled");
501 $mailing = new CRM_Mailing_BAO_Mailing();
502 $mailing->id
= $this->mailing_id
;
503 $mailing->find(TRUE);
507 if ($config == NULL) {
508 $config = CRM_Core_Config
::singleton();
511 if (property_exists($mailing, 'language') && $mailing->language
&& $mailing->language
!= CRM_Core_I18n
::getLocale()) {
512 $swapLang = CRM_Utils_AutoClean
::swap('global://dbLocale?getter', 'call://i18n/setLocale', $mailing->language
);
515 $job_date = CRM_Utils_Date
::isoToMysql($this->scheduled_date
);
518 if (!empty($testParams)) {
519 $mailing->subject
= ts('[CiviMail Draft]') . ' ' . $mailing->subject
;
522 CRM_Mailing_BAO_Mailing
::tokenReplace($mailing);
524 // get and format attachments
525 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_mailing', $mailing->id
);
527 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
528 CRM_Core_Smarty
::registerStringResource();
532 // This handles the edge case scenario where all the mails
533 // have been delivered in prior jobs.
536 // make sure that there's no more than $mailerBatchLimit mails processed in a run
537 $mailerBatchLimit = Civi
::settings()->get('mailerBatchLimit');
538 $eq = self
::findPendingTasks($this->id
, $mailing->sms_provider_id ?
'sms' : 'email');
539 while ($eq->fetch()) {
540 if ($mailerBatchLimit > 0 && self
::$mailsProcessed >= $mailerBatchLimit) {
541 if (!empty($fields)) {
542 $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
546 self
::$mailsProcessed++
;
551 'contact_id' => $eq->contact_id
,
552 'email' => $eq->email
,
553 'phone' => $eq->phone
,
555 if (count($fields) == self
::MAX_CONTACTS_TO_PROCESS
) {
556 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
564 if (!empty($fields)) {
565 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
572 * This is used by CiviMail but will be made redundant by FlexMailer.
573 * @param array $fields
574 * List of intended recipients.
575 * Each recipient is an array with keys 'hash', 'contact_id', 'email', etc.
579 * @param $attachments
584 public function deliverGroup(&$fields, &$mailing, &$mailer, &$job_date, &$attachments) {
585 static $smtpConnectionErrors = 0;
587 if (!is_object($mailer) ||
empty($fields)) {
588 CRM_Core_Error
::fatal();
591 // get the return properties
592 $returnProperties = $mailing->getReturnProperties();
593 $params = $targetParams = $deliveredParams = [];
597 // CRM-15702: Sending bulk sms to contacts without e-mail address fails.
598 // Solution is to skip checking for on hold
599 //do include a statement to check wether e-mail address is on hold
601 if ($mailing->sms_provider_id
) {
602 //do not include a statement to check wether e-mail address is on hold
606 foreach ($fields as $key => $field) {
607 $params[] = $field['contact_id'];
610 $details = CRM_Utils_Token
::getTokenDetails(
613 $skipOnHold, TRUE, NULL,
614 $mailing->getFlattenedTokens(),
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])) {
623 $details[0][$contactID] = [];
626 // Compose the mailing.
627 $recipient = $replyToEmail = NULL;
628 $replyValue = strcmp($mailing->replyto_email
, $mailing->from_email
);
630 $replyToEmail = $mailing->replyto_email
;
633 $message = $mailing->compose(
634 $this->id
, $field['id'], $field['hash'],
635 $field['contact_id'], $field['email'],
636 $recipient, FALSE, $details[0][$contactID], $attachments,
637 FALSE, NULL, $replyToEmail
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
648 $body = $message->get();
649 $headers = $message->headers();
651 if ($mailing->sms_provider_id
) {
652 $provider = CRM_SMS_Provider
::singleton(['mailing_id' => $mailing->id
]);
653 $body = $provider->getMessage($message, $field['contact_id'], $details[0][$contactID]);
654 $headers = $provider->getRecipientDetails($field, $details[0][$contactID]);
657 // make $recipient actually be the *encoded* header, so as not to baffle Mail_RFC822, CRM-5743
658 $recipient = $headers['To'];
661 // disable error reporting on real mailings (but leave error reporting for tests), CRM-5744
663 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
666 $result = $mailer->send($recipient, $headers, $body, $this->id
);
672 if (is_a($result, 'PEAR_Error') && !$mailing->sms_provider_id
) {
674 $message = $result->getMessage();
675 if ($this->isTemporaryError($message)) {
676 // lets log this message and code
677 $code = $result->getCode();
678 CRM_Core_Error
::debug_log_message("SMTP Socket Error or failed to set sender error. Message: $message, Code: $code");
680 // these are socket write errors which most likely means smtp connection errors
681 // lets skip them and reconnect.
682 $smtpConnectionErrors++
;
683 if ($smtpConnectionErrors <= 5) {
684 $mailer->disconnect();
689 // seems like we have too many of them in a row, we should
690 // write stuff to disk and abort the cron job
698 CRM_Core_Error
::debug_log_message("Too many SMTP Socket Errors. Exiting");
699 CRM_Utils_System
::civiExit();
702 // Register the bounce event.
705 'event_queue_id' => $field['id'],
706 'job_id' => $this->id
,
707 'hash' => $field['hash'],
709 $params = array_merge($params,
710 CRM_Mailing_BAO_BouncePattern
::match($result->getMessage())
712 CRM_Mailing_Event_BAO_Bounce
::create($params);
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());
722 // Register the delivery event.
723 $deliveredParams[] = $field['id'];
724 $targetParams[] = $field['contact_id'];
727 if ($count % CRM_Mailing_Config
::BULK_MAIL_INSERT_COUNT
== 0) {
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
739 $status = CRM_Core_DAO
::getFieldValue(
740 'CRM_Mailing_DAO_MailingJob',
747 if ($status != 'Running') {
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--;
761 // If we have enabled the Throttle option, this is the time to enforce it.
762 $mailThrottleTime = Civi
::settings()->get('mailThrottleTime');
763 if (!empty($mailThrottleTime)) {
764 usleep((int ) $mailThrottleTime);
768 $result = $this->writeToDB(
783 * Determine if an SMTP error is temporary or permanent.
785 * @param string $message
786 * PEAR error message.
788 * TRUE - Temporary/retriable error
789 * FALSE - Permanent/non-retriable error
791 protected function isTemporaryError($message) {
792 // SMTP response code is buried in the message.
793 $code = preg_match('/ \(code: (.+), response: /', $message, $matches) ?
$matches[1] : '';
795 if (strpos($message, 'Failed to write to socket') !== FALSE) {
799 // Register 5xx SMTP response code (permanent failure) as bounce.
800 if (isset($code{0}) && $code{0} === '5') {
804 if (strpos($message, 'Failed to set sender') !== FALSE) {
808 if (strpos($message, 'Failed to add recipient') !== FALSE) {
812 if (strpos($message, 'Failed to send data') !== FALSE) {
822 * @param int $mailingId
823 * The id of the mailing to be canceled.
825 public static function cancel($mailingId) {
828 FROM civicrm_mailing_job
829 WHERE mailing_id = %1
831 AND ( ( job_type IS NULL ) OR
832 job_type <> 'child' )
834 $params = [1 => [$mailingId, 'Integer']];
835 $job = CRM_Core_DAO
::executeQuery($sql, $params);
837 in_array($job->status
, ['Scheduled', 'Running', 'Paused'])
840 self
::create(['id' => $job->id
, 'end_date' => date('YmdHis'), 'status' => 'Canceled']);
842 // also cancel all child jobs
844 UPDATE civicrm_mailing_job
845 SET status = 'Canceled',
849 AND job_type = 'child'
850 AND status IN ( 'Scheduled', 'Running', 'Paused' )
853 1 => [$job->id
, 'Integer'],
854 2 => [date('YmdHis'), 'Timestamp'],
856 CRM_Core_DAO
::executeQuery($sql, $params);
863 * @param int $mailingID
864 * The id of the mailing to be paused.
866 public static function pause($mailingID) {
868 UPDATE civicrm_mailing_job
869 SET status = 'Paused'
870 WHERE mailing_id = %1
872 AND status IN ('Scheduled', 'Running')
874 CRM_Core_DAO
::executeQuery($sql, [1 => [$mailingID, 'Integer']]);
880 * @param int $mailingID
881 * The id of the mailing to be resumed.
883 public static function resume($mailingID) {
885 UPDATE civicrm_mailing_job
886 SET status = 'Scheduled'
887 WHERE mailing_id = %1
889 AND start_date IS NULL
890 AND status = 'Paused'
892 CRM_Core_DAO
::executeQuery($sql, [1 => [$mailingID, 'Integer']]);
895 UPDATE civicrm_mailing_job
896 SET status = 'Running'
897 WHERE mailing_id = %1
899 AND start_date IS NOT NULL
900 AND status = 'Paused'
902 CRM_Core_DAO
::executeQuery($sql, [1 => [$mailingID, 'Integer']]);
906 * Return a translated status enum string.
908 * @param string $status
912 * The translated version
914 public static function status($status) {
915 static $translation = NULL;
917 if (empty($translation)) {
919 'Scheduled' => ts('Scheduled'),
920 'Running' => ts('Running'),
921 'Complete' => ts('Complete'),
922 'Paused' => ts('Paused'),
923 'Canceled' => ts('Canceled'),
926 return CRM_Utils_Array
::value($status, $translation, ts('Not scheduled'));
930 * Return a workflow clause for use in SQL queries,
931 * to only process jobs that are approved.
934 * For use in a WHERE clause
936 public static function workflowClause() {
937 // add an additional check and only process
938 // jobs that are approved
939 if (CRM_Mailing_Info
::workflowEnabled()) {
940 $approveOptionID = CRM_Core_PseudoConstant
::getKey('CRM_Mailing_BAO_Mailing', 'approval_status_id', 'Approved');
941 if ($approveOptionID) {
942 return " AND m.approval_status_id = $approveOptionID ";
949 * @param array $deliveredParams
950 * @param array $targetParams
955 * @throws CRM_Core_Exception
958 public function writeToDB(
964 static $activityTypeID = NULL;
965 static $writeActivity = NULL;
967 if (!empty($deliveredParams)) {
968 CRM_Mailing_Event_BAO_Delivered
::bulkCreate($deliveredParams);
969 $deliveredParams = [];
972 if ($writeActivity === NULL) {
973 $writeActivity = Civi
::settings()->get('write_activity_record');
976 if (!$writeActivity) {
981 if (!empty($targetParams) && !empty($mailing->scheduled_id
)) {
982 if (!$activityTypeID) {
983 if ($mailing->sms_provider_id
) {
984 $mailing->subject
= $mailing->name
;
985 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Mass SMS'
989 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Bulk Email');
991 if (!$activityTypeID) {
992 CRM_Core_Error
::fatal();
997 'source_contact_id' => $mailing->scheduled_id
,
999 'target_contact_id' => array_unique($targetParams),
1000 'activity_type_id' => $activityTypeID,
1001 'source_record_id' => $this->mailing_id
,
1002 'activity_date_time' => $job_date,
1003 'subject' => $mailing->subject
,
1004 'status_id' => 'Completed',
1005 'deleteActivityTarget' => FALSE,
1006 'campaign_id' => $mailing->campaign_id
,
1009 //check whether activity is already created for this mailing.
1010 //if yes then create only target contact record.
1013 FROM civicrm_activity
1014 WHERE civicrm_activity.activity_type_id = %1
1015 AND civicrm_activity.source_record_id = %2
1019 1 => [$activityTypeID, 'Integer'],
1020 2 => [$this->mailing_id
, 'Integer'],
1022 $activityID = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
1025 $activity['id'] = $activityID;
1028 if (CRM_Core_BAO_Email
::isMultipleBulkMail()) {
1029 static $targetRecordID = NULL;
1030 if (!$targetRecordID) {
1031 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1032 $targetRecordID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1035 // make sure we don't attempt to duplicate the target activity
1036 foreach ($activity['target_contact_id'] as $key => $targetID) {
1039 FROM civicrm_activity_contact
1040 WHERE activity_id = $activityID
1041 AND contact_id = $targetID
1042 AND record_type_id = $targetRecordID
1044 if (CRM_Core_DAO
::singleValueQuery($sql)) {
1045 unset($activity['target_contact_id'][$key]);
1052 civicrm_api3('Activity', 'create', $activity);
1054 catch (Exception
$e) {
1065 * Search the mailing-event queue for a list of pending delivery tasks.
1068 * @param string $medium
1069 * Ex: 'email' or 'sms'.
1071 * @return \CRM_Mailing_Event_BAO_Queue
1072 * A query object whose rows provide ('id', 'contact_id', 'hash') and ('email' or 'phone').
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();
1078 $phoneTable = CRM_Core_BAO_Phone
::getTableName();
1079 $contactTable = CRM_Contact_BAO_Contact
::getTableName();
1080 $deliveredTable = CRM_Mailing_Event_BAO_Delivered
::getTableName();
1081 $bounceTable = CRM_Mailing_Event_BAO_Bounce
::getTableName();
1083 $query = " SELECT $queueTable.id,
1084 $emailTable.email as email,
1085 $queueTable.contact_id,
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";
1102 if ($medium === 'sms') {
1104 SELECT $queueTable.id,
1105 $phoneTable.phone as phone,
1106 $queueTable.contact_id,
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 )";
1129 * Delete the mailing job.
1136 public static function del($id) {
1137 CRM_Utils_Hook
::pre('delete', 'MailingJob', $id, CRM_Core_DAO
::$_nullArray);
1139 $jobDAO = new CRM_Mailing_BAO_MailingJob();
1141 $result = $jobDAO->delete();
1143 CRM_Utils_Hook
::post('delete', 'MailingJob', $jobDAO->id
, $jobDAO);