3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 require_once 'Mail.php';
21 * Class CRM_Mailing_BAO_MailingJob
23 class CRM_Mailing_BAO_MailingJob
extends CRM_Mailing_DAO_MailingJob
{
24 const MAX_CONTACTS_TO_PROCESS
= 1000;
27 * (Dear God Why) Keep a global count of mails processed within the current
32 public static $mailsProcessed = 0;
37 public function __construct() {
38 parent
::__construct();
44 * @param array $params
46 * @return \CRM_Mailing_BAO_MailingJob
47 * @throws \CRM_Core_Exception
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");
53 $op = empty($params['id']) ?
'create' : 'edit';
54 CRM_Utils_Hook
::pre($op, 'MailingJob', CRM_Utils_Array
::value('id', $params), $params);
56 $jobDAO = new CRM_Mailing_BAO_MailingJob();
57 $jobDAO->copyValues($params);
59 if (!empty($params['mailing_id']) && empty('is_calling_function_updated_to_reflect_deprecation')) {
60 CRM_Mailing_BAO_Mailing
::getRecipients($params['mailing_id']);
62 CRM_Utils_Hook
::post($op, 'MailingJob', $jobDAO->id
, $jobDAO);
67 * Initiate all pending/ready jobs.
69 * @param array $testParams
74 public static function runJobs($testParams = NULL, $mode = NULL) {
75 $job = new CRM_Mailing_BAO_MailingJob();
77 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
78 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
79 $mailerBatchLimit = Civi
::settings()->get('mailerBatchLimit');
81 if (!empty($testParams)) {
85 WHERE id = {$testParams['job_id']}";
89 $currentTime = date('YmdHis');
90 $mailingACL = CRM_Mailing_BAO_Mailing
::mailingACL('m');
91 $domainID = CRM_Core_Config
::domainID();
93 $modeClause = 'AND m.sms_provider_id IS NULL';
95 $modeClause = 'AND m.sms_provider_id IS NOT NULL';
98 // Select the first child job that is scheduled
104 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
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')
114 ORDER BY j.scheduled_date ASC,
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()) {
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',
142 $job->status
!= 'Running' &&
143 $job->status
!= 'Scheduled'
145 // this includes Cancelled and other statuses, CRM-4246
151 /* Queue up recipients for the child job being launched */
153 if ($job->status
!= 'Running') {
154 $transaction = new CRM_Core_Transaction();
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);
160 // Update to show job has started.
163 'start_date' => date('YmdHis'),
164 'status' => 'Running',
167 $transaction->commit();
171 if ($mode === NULL) {
172 $mailer = \Civi
::service('pear_mail');
174 elseif ($mode == 'sms') {
175 $mailer = CRM_SMS_Provider
::singleton(['mailing_id' => $job->mailing_id
]);
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]);
183 $isComplete = $job->deliver($mailer, $testParams);
186 CRM_Utils_Hook
::post('create', 'CRM_Mailing_DAO_Spool', $job->id
, $isComplete);
188 // Mark the child complete
192 $transaction = new CRM_Core_Transaction();
193 self
::create(['id' => $job->id
, 'end_date' => date('YmdHis'), 'status' => 'Complete']);
194 $transaction->commit();
196 // don't mark the mailing as complete
199 // Release the child joblock
206 // CRM-17629: Stop processing jobs if mailer batch limit reached
207 if ($mailerBatchLimit > 0 && self
::$mailsProcessed >= $mailerBatchLimit) {
215 * Post process to determine if the parent job
216 * as well as the mailing is complete after the run.
219 public static function runJobs_post($mode = NULL) {
221 $job = new CRM_Mailing_BAO_MailingJob();
223 $mailing = new CRM_Mailing_BAO_Mailing();
225 $config = CRM_Core_Config
::singleton();
226 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
227 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
229 $currentTime = date('YmdHis');
230 $mailingACL = CRM_Mailing_BAO_Mailing
::mailingACL('m');
231 $domainID = CRM_Core_Config
::domainID();
237 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
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,
248 // For each parent job that is running, let's look at their child jobs
249 while ($job->fetch()) {
251 $child_job = new CRM_Mailing_BAO_MailingJob();
255 FROM civicrm_mailing_job j, civicrm_mailing m
256 WHERE m.id = j.mailing_id
257 AND j.job_type = 'child'
259 AND j.status <> 'Complete'";
260 $params = [1 => [$job->id
, 'Integer']];
262 $anyChildLeft = CRM_Core_DAO
::singleValueQuery($child_job_sql, $params);
264 // all of the child jobs are complete, update
265 // the parent job as well as the mailing status
266 if (!$anyChildLeft) {
268 $transaction = new CRM_Core_Transaction();
270 $saveJob = new CRM_Mailing_DAO_MailingJob();
271 $saveJob->id
= $job->id
;
272 $saveJob->end_date
= date('YmdHis');
273 $saveJob->status
= 'Complete';
277 $mailing->id
= $job->mailing_id
;
278 $mailing->is_completed
= TRUE;
280 $transaction->commit();
283 CRM_Utils_Hook
::postMailing($job->mailing_id
);
289 * before we run jobs, we need to split the jobs
293 public static function runJobs_pre($offset = 200, $mode = NULL) {
294 $job = new CRM_Mailing_BAO_MailingJob();
296 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
297 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
299 $currentTime = date('YmdHis');
300 $mailingACL = CRM_Mailing_BAO_Mailing
::mailingACL('m');
302 $workflowClause = CRM_Mailing_BAO_MailingJob
::workflowClause();
304 $domainID = CRM_Core_Config
::domainID();
306 $modeClause = 'AND m.sms_provider_id IS NULL';
307 if ($mode == 'sms') {
308 $modeClause = 'AND m.sms_provider_id IS NOT NULL';
311 // Select all the mailing jobs that are created from
312 // when the mailing is submitted or scheduled.
317 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
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,
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()) {
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',
350 if ($job->status
!= 'Scheduled') {
355 $transaction = new CRM_Core_Transaction();
357 $job->split_job($offset);
359 // Update the status of the parent job
360 self
::create(['id' => $job->id
, 'start_date' => date('YmdHis'), 'status' => 'Running']);
361 $transaction->commit();
363 // Release the job lock
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
373 public function split_job($offset = 200) {
374 $recipient_count = CRM_Mailing_BAO_Recipients
::mailingSize($this->mailing_id
);
376 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
378 $dao = new CRM_Core_DAO();
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)
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'],
392 7 => [$recipient_count, 'Integer'],
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
400 CRM_Core_DAO
::executeQuery($sql, $params);
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);
408 $params[7][0] = $offset;
409 CRM_Core_DAO
::executeQuery($sql, $params);
416 * @param array $testParams
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);
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
);
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
435 while ($recipients->fetch()) {
436 // CRM-18543: there are situations when both the email and phone are null.
437 // Skip the recipient in this case.
438 if (empty($recipients->email_id
) && empty($recipients->phone_id
)) {
442 if ($recipients->phone_id
) {
443 $recipients->email_id
= "null";
446 $recipients->phone_id
= "null";
451 $recipients->email_id
,
452 $recipients->contact_id
,
453 $recipients->phone_id
,
456 if ($count % CRM_Mailing_Config
::BULK_MAIL_INSERT_COUNT
== 0) {
457 CRM_Mailing_Event_BAO_Queue
::bulkCreate($params, $now);
463 if (!empty($params)) {
464 CRM_Mailing_Event_BAO_Queue
::bulkCreate($params, $now);
473 * This is used by CiviMail but will be made redundant by FlexMailer.
474 * @param object $mailer
475 * A Mail object to send the messages.
477 * @param array $testParams
480 public function deliver(&$mailer, $testParams = NULL) {
481 if (\Civi
::settings()->get('experimentalFlexMailerEngine')) {
482 throw new \
RuntimeException("Cannot use legacy deliver() when experimentalFlexMailerEngine is enabled");
485 $mailing = new CRM_Mailing_BAO_Mailing();
486 $mailing->id
= $this->mailing_id
;
487 $mailing->find(TRUE);
491 if ($config == NULL) {
492 $config = CRM_Core_Config
::singleton();
495 if (property_exists($mailing, 'language') && $mailing->language
&& $mailing->language
!= CRM_Core_I18n
::getLocale()) {
496 $swapLang = CRM_Utils_AutoClean
::swap('global://dbLocale?getter', 'call://i18n/setLocale', $mailing->language
);
499 $job_date = CRM_Utils_Date
::isoToMysql($this->scheduled_date
);
502 if (!empty($testParams)) {
503 $mailing->subject
= ts('[CiviMail Draft]') . ' ' . $mailing->subject
;
506 CRM_Mailing_BAO_Mailing
::tokenReplace($mailing);
508 // get and format attachments
509 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_mailing', $mailing->id
);
511 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
512 CRM_Core_Smarty
::registerStringResource();
516 // This handles the edge case scenario where all the mails
517 // have been delivered in prior jobs.
520 // make sure that there's no more than $mailerBatchLimit mails processed in a run
521 $mailerBatchLimit = Civi
::settings()->get('mailerBatchLimit');
522 $eq = self
::findPendingTasks($this->id
, $mailing->sms_provider_id ?
'sms' : 'email');
523 while ($eq->fetch()) {
524 if ($mailerBatchLimit > 0 && self
::$mailsProcessed >= $mailerBatchLimit) {
525 if (!empty($fields)) {
526 $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
530 self
::$mailsProcessed++
;
535 'contact_id' => $eq->contact_id
,
536 'email' => $eq->email
,
537 'phone' => $eq->phone
,
539 if (count($fields) == self
::MAX_CONTACTS_TO_PROCESS
) {
540 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
548 if (!empty($fields)) {
549 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
556 * This is used by CiviMail but will be made redundant by FlexMailer.
557 * @param array $fields
558 * List of intended recipients.
559 * Each recipient is an array with keys 'hash', 'contact_id', 'email', etc.
563 * @param $attachments
568 public function deliverGroup(&$fields, &$mailing, &$mailer, &$job_date, &$attachments) {
569 static $smtpConnectionErrors = 0;
571 if (!is_object($mailer) ||
empty($fields)) {
572 throw new CRM_Core_Exception('Either mailer is not an object or we don\'t have recipients to send to in this group');
575 // get the return properties
576 $returnProperties = $mailing->getReturnProperties();
577 $params = $targetParams = $deliveredParams = [];
581 // CRM-15702: Sending bulk sms to contacts without e-mail address fails.
582 // Solution is to skip checking for on hold
583 //do include a statement to check wether e-mail address is on hold
585 if ($mailing->sms_provider_id
) {
586 //do not include a statement to check wether e-mail address is on hold
590 foreach ($fields as $key => $field) {
591 $params[] = $field['contact_id'];
594 $details = CRM_Utils_Token
::getTokenDetails(
597 $skipOnHold, TRUE, NULL,
598 $mailing->getFlattenedTokens(),
603 $config = CRM_Core_Config
::singleton();
604 foreach ($fields as $key => $field) {
605 $contactID = $field['contact_id'];
606 if (!array_key_exists($contactID, $details[0])) {
607 $details[0][$contactID] = [];
610 // Compose the mailing.
611 $recipient = $replyToEmail = NULL;
612 $replyValue = strcmp($mailing->replyto_email
, $mailing->from_email
);
614 $replyToEmail = $mailing->replyto_email
;
617 $message = $mailing->compose(
618 $this->id
, $field['id'], $field['hash'],
619 $field['contact_id'], $field['email'],
620 $recipient, FALSE, $details[0][$contactID], $attachments,
621 FALSE, NULL, $replyToEmail
623 if (empty($message)) {
624 // lets keep the message in the queue
625 // most likely a permissions related issue with smarty templates
626 // or a bad contact id? CRM-9833
632 $body = $message->get();
633 $headers = $message->headers();
635 if ($mailing->sms_provider_id
) {
636 $provider = CRM_SMS_Provider
::singleton(['mailing_id' => $mailing->id
]);
637 $body = $provider->getMessage($message, $field['contact_id'], $details[0][$contactID]);
638 $headers = $provider->getRecipientDetails($field, $details[0][$contactID]);
641 // make $recipient actually be the *encoded* header, so as not to baffle Mail_RFC822, CRM-5743
642 $recipient = $headers['To'];
645 // disable error reporting on real mailings (but leave error reporting for tests), CRM-5744
647 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
650 $result = $mailer->send($recipient, $headers, $body, $this->id
);
656 if (is_a($result, 'PEAR_Error') && !$mailing->sms_provider_id
) {
658 $message = $result->getMessage();
659 if ($this->isTemporaryError($message)) {
660 // lets log this message and code
661 $code = $result->getCode();
662 CRM_Core_Error
::debug_log_message("SMTP Socket Error or failed to set sender error. Message: $message, Code: $code");
664 // these are socket write errors which most likely means smtp connection errors
665 // lets skip them and reconnect.
666 $smtpConnectionErrors++
;
667 if ($smtpConnectionErrors <= 5) {
668 $mailer->disconnect();
673 // seems like we have too many of them in a row, we should
674 // write stuff to disk and abort the cron job
682 CRM_Core_Error
::debug_log_message("Too many SMTP Socket Errors. Exiting");
683 CRM_Utils_System
::civiExit();
686 // Register the bounce event.
689 'event_queue_id' => $field['id'],
690 'job_id' => $this->id
,
691 'hash' => $field['hash'],
693 $params = array_merge($params,
694 CRM_Mailing_BAO_BouncePattern
::match($result->getMessage())
696 CRM_Mailing_Event_BAO_Bounce
::create($params);
698 elseif (is_a($result, 'PEAR_Error') && $mailing->sms_provider_id
) {
699 // Handle SMS errors: CRM-15426
700 $job_id = intval($this->id
);
701 $mailing_id = intval($mailing->id
);
702 CRM_Core_Error
::debug_log_message("Failed to send SMS message. Vars: mailing_id: ${mailing_id}, job_id: ${job_id}. Error message follows.");
703 CRM_Core_Error
::debug_log_message($result->getMessage());
706 // Register the delivery event.
707 $deliveredParams[] = $field['id'];
708 $targetParams[] = $field['contact_id'];
711 if ($count % CRM_Mailing_Config
::BULK_MAIL_INSERT_COUNT
== 0) {
720 // hack to stop mailing job at run time, CRM-4246.
721 // to avoid making too many DB calls for this rare case
722 // lets do it when we snapshot
723 $status = CRM_Core_DAO
::getFieldValue(
724 'CRM_Mailing_DAO_MailingJob',
731 if ($status != 'Running') {
739 // seems like a successful delivery or bounce, lets decrement error count
740 // only if we have smtp connection errors
741 if ($smtpConnectionErrors > 0) {
742 $smtpConnectionErrors--;
745 // If we have enabled the Throttle option, this is the time to enforce it.
746 $mailThrottleTime = Civi
::settings()->get('mailThrottleTime');
747 if (!empty($mailThrottleTime)) {
748 usleep((int ) $mailThrottleTime);
752 $result = $this->writeToDB(
767 * Determine if an SMTP error is temporary or permanent.
769 * @param string $message
770 * PEAR error message.
772 * TRUE - Temporary/retriable error
773 * FALSE - Permanent/non-retriable error
775 protected function isTemporaryError($message) {
776 // SMTP response code is buried in the message.
777 $code = preg_match('/ \(code: (.+), response: /', $message, $matches) ?
$matches[1] : '';
779 if (strpos($message, 'Failed to write to socket') !== FALSE) {
783 // Register 5xx SMTP response code (permanent failure) as bounce.
784 if (isset($code[0]) && $code[0] === '5') {
788 if (strpos($message, 'Failed to set sender') !== FALSE) {
792 if (strpos($message, 'Failed to add recipient') !== FALSE) {
796 if (strpos($message, 'Failed to send data') !== FALSE) {
806 * @param int $mailingId
807 * The id of the mailing to be canceled.
809 public static function cancel($mailingId) {
812 FROM civicrm_mailing_job
813 WHERE mailing_id = %1
815 AND ( ( job_type IS NULL ) OR
816 job_type <> 'child' )
818 $params = [1 => [$mailingId, 'Integer']];
819 $job = CRM_Core_DAO
::executeQuery($sql, $params);
821 in_array($job->status
, ['Scheduled', 'Running', 'Paused'])
824 self
::create(['id' => $job->id
, 'end_date' => date('YmdHis'), 'status' => 'Canceled']);
826 // also cancel all child jobs
828 UPDATE civicrm_mailing_job
829 SET status = 'Canceled',
833 AND job_type = 'child'
834 AND status IN ( 'Scheduled', 'Running', 'Paused' )
837 1 => [$job->id
, 'Integer'],
838 2 => [date('YmdHis'), 'Timestamp'],
840 CRM_Core_DAO
::executeQuery($sql, $params);
847 * @param int $mailingID
848 * The id of the mailing to be paused.
850 public static function pause($mailingID) {
852 UPDATE civicrm_mailing_job
853 SET status = 'Paused'
854 WHERE mailing_id = %1
856 AND status IN ('Scheduled', 'Running')
858 CRM_Core_DAO
::executeQuery($sql, [1 => [$mailingID, 'Integer']]);
864 * @param int $mailingID
865 * The id of the mailing to be resumed.
867 public static function resume($mailingID) {
869 UPDATE civicrm_mailing_job
870 SET status = 'Scheduled'
871 WHERE mailing_id = %1
873 AND start_date IS NULL
874 AND status = 'Paused'
876 CRM_Core_DAO
::executeQuery($sql, [1 => [$mailingID, 'Integer']]);
879 UPDATE civicrm_mailing_job
880 SET status = 'Running'
881 WHERE mailing_id = %1
883 AND start_date IS NOT NULL
884 AND status = 'Paused'
886 CRM_Core_DAO
::executeQuery($sql, [1 => [$mailingID, 'Integer']]);
890 * Return a translated status enum string.
892 * @param string $status
896 * The translated version
898 public static function status($status) {
899 static $translation = NULL;
901 if (empty($translation)) {
903 'Scheduled' => ts('Scheduled'),
904 'Running' => ts('Running'),
905 'Complete' => ts('Complete'),
906 'Paused' => ts('Paused'),
907 'Canceled' => ts('Canceled'),
910 return CRM_Utils_Array
::value($status, $translation, ts('Not scheduled'));
914 * Return a workflow clause for use in SQL queries,
915 * to only process jobs that are approved.
918 * For use in a WHERE clause
920 public static function workflowClause() {
921 // add an additional check and only process
922 // jobs that are approved
923 if (CRM_Mailing_Info
::workflowEnabled()) {
924 $approveOptionID = CRM_Core_PseudoConstant
::getKey('CRM_Mailing_BAO_Mailing', 'approval_status_id', 'Approved');
925 if ($approveOptionID) {
926 return " AND m.approval_status_id = $approveOptionID ";
933 * @param array $deliveredParams
934 * @param array $targetParams
939 * @throws CRM_Core_Exception
942 public function writeToDB(
948 static $activityTypeID = NULL;
949 static $writeActivity = NULL;
951 if (!empty($deliveredParams)) {
952 CRM_Mailing_Event_BAO_Delivered
::bulkCreate($deliveredParams);
953 $deliveredParams = [];
956 if ($writeActivity === NULL) {
957 $writeActivity = Civi
::settings()->get('write_activity_record');
960 if (!$writeActivity) {
965 if (!empty($targetParams) && !empty($mailing->scheduled_id
)) {
966 if (!$activityTypeID) {
967 if ($mailing->sms_provider_id
) {
968 $mailing->subject
= $mailing->name
;
969 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Mass SMS'
973 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Bulk Email');
975 if (!$activityTypeID) {
976 throw new CRM_Core_Execption(ts('No relevant activity type found when recording Mailing Event delivered Activity'));
981 'source_contact_id' => $mailing->scheduled_id
,
983 'target_contact_id' => array_unique($targetParams),
984 'activity_type_id' => $activityTypeID,
985 'source_record_id' => $this->mailing_id
,
986 'activity_date_time' => $job_date,
987 'subject' => $mailing->subject
,
988 'status_id' => 'Completed',
989 'deleteActivityTarget' => FALSE,
990 'campaign_id' => $mailing->campaign_id
,
993 //check whether activity is already created for this mailing.
994 //if yes then create only target contact record.
997 FROM civicrm_activity
998 WHERE civicrm_activity.activity_type_id = %1
999 AND civicrm_activity.source_record_id = %2
1003 1 => [$activityTypeID, 'Integer'],
1004 2 => [$this->mailing_id
, 'Integer'],
1006 $activityID = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
1009 $activity['id'] = $activityID;
1012 if (CRM_Core_BAO_Email
::isMultipleBulkMail()) {
1013 static $targetRecordID = NULL;
1014 if (!$targetRecordID) {
1015 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1016 $targetRecordID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1019 // make sure we don't attempt to duplicate the target activity
1020 foreach ($activity['target_contact_id'] as $key => $targetID) {
1023 FROM civicrm_activity_contact
1024 WHERE activity_id = $activityID
1025 AND contact_id = $targetID
1026 AND record_type_id = $targetRecordID
1028 if (CRM_Core_DAO
::singleValueQuery($sql)) {
1029 unset($activity['target_contact_id'][$key]);
1036 civicrm_api3('Activity', 'create', $activity);
1038 catch (Exception
$e) {
1049 * Search the mailing-event queue for a list of pending delivery tasks.
1052 * @param string $medium
1053 * Ex: 'email' or 'sms'.
1055 * @return \CRM_Mailing_Event_BAO_Queue
1056 * A query object whose rows provide ('id', 'contact_id', 'hash') and ('email' or 'phone').
1058 public static function findPendingTasks($jobId, $medium) {
1059 $eq = new CRM_Mailing_Event_BAO_Queue();
1060 $queueTable = CRM_Mailing_Event_BAO_Queue
::getTableName();
1061 $emailTable = CRM_Core_BAO_Email
::getTableName();
1062 $phoneTable = CRM_Core_BAO_Phone
::getTableName();
1063 $contactTable = CRM_Contact_BAO_Contact
::getTableName();
1064 $deliveredTable = CRM_Mailing_Event_BAO_Delivered
::getTableName();
1065 $bounceTable = CRM_Mailing_Event_BAO_Bounce
::getTableName();
1067 $query = " SELECT $queueTable.id,
1068 $emailTable.email as email,
1069 $queueTable.contact_id,
1073 INNER JOIN $emailTable
1074 ON $queueTable.email_id = $emailTable.id
1075 INNER JOIN $contactTable
1076 ON $contactTable.id = $emailTable.contact_id
1077 LEFT JOIN $deliveredTable
1078 ON $queueTable.id = $deliveredTable.event_queue_id
1079 LEFT JOIN $bounceTable
1080 ON $queueTable.id = $bounceTable.event_queue_id
1081 WHERE $queueTable.job_id = " . $jobId . "
1082 AND $deliveredTable.id IS null
1083 AND $bounceTable.id IS null
1084 AND $contactTable.is_opt_out = 0";
1086 if ($medium === 'sms') {
1088 SELECT $queueTable.id,
1089 $phoneTable.phone as phone,
1090 $queueTable.contact_id,
1094 INNER JOIN $phoneTable
1095 ON $queueTable.phone_id = $phoneTable.id
1096 INNER JOIN $contactTable
1097 ON $contactTable.id = $phoneTable.contact_id
1098 LEFT JOIN $deliveredTable
1099 ON $queueTable.id = $deliveredTable.event_queue_id
1100 LEFT JOIN $bounceTable
1101 ON $queueTable.id = $bounceTable.event_queue_id
1102 WHERE $queueTable.job_id = " . $jobId . "
1103 AND $deliveredTable.id IS null
1104 AND $bounceTable.id IS null
1105 AND ( $contactTable.is_opt_out = 0
1106 OR $contactTable.do_not_sms = 0 )";
1113 * Delete the mailing job.
1120 public static function del($id) {
1121 CRM_Utils_Hook
::pre('delete', 'MailingJob', $id, CRM_Core_DAO
::$_nullArray);
1123 $jobDAO = new CRM_Mailing_BAO_MailingJob();
1125 $result = $jobDAO->delete();
1127 CRM_Utils_Hook
::post('delete', 'MailingJob', $jobDAO->id
, $jobDAO);