3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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 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 static public function create($params) {
66 $job = new CRM_Mailing_BAO_MailingJob();
67 $job->mailing_id
= $params['mailing_id'];
68 $job->status
= $params['status'];
69 $job->scheduled_date
= $params['scheduled_date'];
70 $job->is_test
= $params['is_test'];
72 if ($params['mailing_id']) {
73 CRM_Mailing_BAO_Mailing
::getRecipients($params['mailing_id']);
77 throw new CRM_Core_Exception("Failed to create job: Unknown mailing ID");
82 * Initiate all pending/ready jobs.
84 * @param array $testParams
89 public static function runJobs($testParams = NULL, $mode = NULL) {
90 $job = new CRM_Mailing_BAO_MailingJob();
92 $config = CRM_Core_Config
::singleton();
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 // Mark up the starting time
177 $saveJob = new CRM_Mailing_DAO_MailingJob();
178 $saveJob->id
= $job->id
;
179 $saveJob->start_date
= date('YmdHis');
180 $saveJob->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(array('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
, array($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();
210 $saveJob = new CRM_Mailing_DAO_MailingJob();
211 $saveJob->id
= $job->id
;
212 $saveJob->end_date
= date('YmdHis');
213 $saveJob->status
= 'Complete';
216 $transaction->commit();
218 // don't mark the mailing as complete
221 // Release the child joblock
228 // CRM-17629: Stop processing jobs if mailer batch limit reached
229 if ($mailerBatchLimit > 0 && self
::$mailsProcessed >= $mailerBatchLimit) {
237 * Post process to determine if the parent job
238 * as well as the mailing is complete after the run.
241 public static function runJobs_post($mode = NULL) {
243 $job = new CRM_Mailing_BAO_MailingJob();
245 $mailing = new CRM_Mailing_BAO_Mailing();
247 $config = CRM_Core_Config
::singleton();
248 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
249 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
251 $currentTime = date('YmdHis');
252 $mailingACL = CRM_Mailing_BAO_Mailing
::mailingACL('m');
253 $domainID = CRM_Core_Config
::domainID();
259 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
261 AND j.scheduled_date <= $currentTime
262 AND j.status = 'Running'
263 AND j.end_date IS null
264 AND (j.job_type != 'child' OR j.job_type is NULL)
265 ORDER BY j.scheduled_date,
270 // For each parent job that is running, let's look at their child jobs
271 while ($job->fetch()) {
273 $child_job = new CRM_Mailing_BAO_MailingJob();
277 FROM civicrm_mailing_job j, civicrm_mailing m
278 WHERE m.id = j.mailing_id
279 AND j.job_type = 'child'
281 AND j.status <> 'Complete'";
282 $params = array(1 => array($job->id
, 'Integer'));
284 $anyChildLeft = CRM_Core_DAO
::singleValueQuery($child_job_sql, $params);
286 // all of the child jobs are complete, update
287 // the parent job as well as the mailing status
288 if (!$anyChildLeft) {
290 $transaction = new CRM_Core_Transaction();
292 $saveJob = new CRM_Mailing_DAO_MailingJob();
293 $saveJob->id
= $job->id
;
294 $saveJob->end_date
= date('YmdHis');
295 $saveJob->status
= 'Complete';
299 $mailing->id
= $job->mailing_id
;
300 $mailing->is_completed
= TRUE;
302 $transaction->commit();
305 CRM_Utils_Hook
::postMailing($job->mailing_id
);
312 * before we run jobs, we need to split the jobs
316 public static function runJobs_pre($offset = 200, $mode = NULL) {
317 $job = new CRM_Mailing_BAO_MailingJob();
319 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
320 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
322 $currentTime = date('YmdHis');
323 $mailingACL = CRM_Mailing_BAO_Mailing
::mailingACL('m');
325 $workflowClause = CRM_Mailing_BAO_MailingJob
::workflowClause();
327 $domainID = CRM_Core_Config
::domainID();
329 $modeClause = 'AND m.sms_provider_id IS NULL';
330 if ($mode == 'sms') {
331 $modeClause = 'AND m.sms_provider_id IS NOT NULL';
334 // Select all the mailing jobs that are created from
335 // when the mailing is submitted or scheduled.
340 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
344 AND ( ( j.start_date IS null
345 AND j.scheduled_date <= $currentTime
346 AND j.status = 'Scheduled'
347 AND j.end_date IS null ) )
348 AND ((j.job_type is NULL) OR (j.job_type <> 'child'))
349 ORDER BY j.scheduled_date,
354 // For each of the "Parent Jobs" we find, we split them into
355 // X Number of child jobs
356 while ($job->fetch()) {
357 // still use job level lock for each child job
358 $lock = Civi
::lockManager()->acquire("data.mailing.job.{$job->id}");
359 if (!$lock->isAcquired()) {
363 // Re-fetch the job status in case things
364 // changed between the first query and now
365 // to avoid race conditions
366 $job->status
= CRM_Core_DAO
::getFieldValue(
367 'CRM_Mailing_DAO_MailingJob',
373 if ($job->status
!= 'Scheduled') {
378 $transaction = new CRM_Core_Transaction();
380 $job->split_job($offset);
382 // update the status of the parent job
383 $saveJob = new CRM_Mailing_DAO_MailingJob();
384 $saveJob->id
= $job->id
;
385 $saveJob->start_date
= date('YmdHis');
386 $saveJob->status
= 'Running';
389 $transaction->commit();
391 // Release the job lock
397 * Split the parent job into n number of child job based on an offset.
398 * If null or 0 , we create only one child job
401 public function split_job($offset = 200) {
402 $recipient_count = CRM_Mailing_BAO_Recipients
::mailingSize($this->mailing_id
);
404 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
406 $dao = new CRM_Core_DAO();
409 INSERT INTO civicrm_mailing_job
410 (`mailing_id`, `scheduled_date`, `status`, `job_type`, `parent_id`, `job_offset`, `job_limit`)
411 VALUES (%1, %2, %3, %4, %5, %6, %7)
414 1 => array($this->mailing_id
, 'Integer'),
415 2 => array($this->scheduled_date
, 'String'),
416 3 => array('Scheduled', 'String'),
417 4 => array('child', 'String'),
418 5 => array($this->id
, 'Integer'),
419 6 => array(0, 'Integer'),
420 7 => array($recipient_count, 'Integer'),
423 // create one child job if the mailing size is less than the offset
424 // probably use a CRM_Mailing_DAO_MailingJob( );
425 if (empty($offset) ||
426 $recipient_count <= $offset
428 CRM_Core_DAO
::executeQuery($sql, $params);
431 // Creating 'child jobs'
432 $scheduled_unixtime = strtotime($this->scheduled_date
);
433 for ($i = 0, $s = 0; $i < $recipient_count; $i = $i +
$offset, $s++
) {
434 $params[2][0] = date('Y-m-d H:i:s', $scheduled_unixtime +
$s);
436 $params[7][0] = $offset;
437 CRM_Core_DAO
::executeQuery($sql, $params);
444 * @param array $testParams
446 public function queue($testParams = NULL) {
447 $mailing = new CRM_Mailing_BAO_Mailing();
448 $mailing->id
= $this->mailing_id
;
449 if (!empty($testParams)) {
450 $mailing->getTestRecipients($testParams);
453 // We are still getting all the recipients from the parent job
454 // so we don't mess with the include/exclude logic.
455 $recipients = CRM_Mailing_BAO_Recipients
::mailingQuery($this->mailing_id
, $this->job_offset
, $this->job_limit
);
457 // FIXME: this is not very smart, we should move this to one DB call
458 // INSERT INTO ... SELECT FROM ..
459 // the thing we need to figure out is how to generate the hash automatically
463 while ($recipients->fetch()) {
464 // CRM-18543: there are situations when both the email and phone are null.
465 // Skip the recipient in this case.
466 if (empty($recipients->email_id
) && empty($recipients->phone_id
)) {
470 if ($recipients->phone_id
) {
471 $recipients->email_id
= "null";
474 $recipients->phone_id
= "null";
479 $recipients->email_id
,
480 $recipients->contact_id
,
481 $recipients->phone_id
,
484 if ($count % CRM_Mailing_Config
::BULK_MAIL_INSERT_COUNT
== 0) {
485 CRM_Mailing_Event_BAO_Queue
::bulkCreate($params, $now);
491 if (!empty($params)) {
492 CRM_Mailing_Event_BAO_Queue
::bulkCreate($params, $now);
501 * This is used by CiviMail but will be made redundant by FlexMailer.
502 * @param object $mailer
503 * A Mail object to send the messages.
505 * @param array $testParams
508 public function deliver(&$mailer, $testParams = NULL) {
509 if (\Civi
::settings()->get('experimentalFlexMailerEngine')) {
510 throw new \
RuntimeException("Cannot use legacy deliver() when experimentalFlexMailerEngine is enabled");
513 $mailing = new CRM_Mailing_BAO_Mailing();
514 $mailing->id
= $this->mailing_id
;
515 $mailing->find(TRUE);
520 if ($config == NULL) {
521 $config = CRM_Core_Config
::singleton();
524 if (property_exists($mailing, 'language') && $mailing->language
&& $mailing->language
!= 'en_US') {
525 $swapLang = CRM_Utils_AutoClean
::swap('global://dbLocale?getter', 'call://i18n/setLocale', $mailing->language
);
528 $job_date = CRM_Utils_Date
::isoToMysql($this->scheduled_date
);
531 if (!empty($testParams)) {
532 $mailing->subject
= ts('[CiviMail Draft]') . ' ' . $mailing->subject
;
535 CRM_Mailing_BAO_Mailing
::tokenReplace($mailing);
537 // get and format attachments
538 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_mailing', $mailing->id
);
540 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
541 CRM_Core_Smarty
::registerStringResource();
545 // This handles the edge case scenario where all the mails
546 // have been delivered in prior jobs.
549 // make sure that there's no more than $mailerBatchLimit mails processed in a run
550 $mailerBatchLimit = Civi
::settings()->get('mailerBatchLimit');
551 $eq = self
::findPendingTasks($this->id
, $mailing->sms_provider_id ?
'sms' : 'email');
552 while ($eq->fetch()) {
553 if ($mailerBatchLimit > 0 && self
::$mailsProcessed >= $mailerBatchLimit) {
554 if (!empty($fields)) {
555 $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
560 self
::$mailsProcessed++
;
565 'contact_id' => $eq->contact_id
,
566 'email' => $eq->email
,
567 'phone' => $eq->phone
,
569 if (count($fields) == self
::MAX_CONTACTS_TO_PROCESS
) {
570 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
581 if (!empty($fields)) {
582 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
589 * This is used by CiviMail but will be made redundant by FlexMailer.
590 * @param array $fields
591 * List of intended recipients.
592 * Each recipient is an array with keys 'hash', 'contact_id', 'email', etc.
596 * @param $attachments
601 public function deliverGroup(&$fields, &$mailing, &$mailer, &$job_date, &$attachments) {
602 static $smtpConnectionErrors = 0;
604 if (!is_object($mailer) ||
empty($fields)) {
605 CRM_Core_Error
::fatal();
608 // get the return properties
609 $returnProperties = $mailing->getReturnProperties();
610 $params = $targetParams = $deliveredParams = array();
613 // CRM-15702: Sending bulk sms to contacts without e-mail address fails.
614 // Solution is to skip checking for on hold
615 $skipOnHold = TRUE; //do include a statement to check wether e-mail address is on hold
616 if ($mailing->sms_provider_id
) {
617 $skipOnHold = FALSE; //do not include a statement to check wether e-mail address is on hold
620 foreach ($fields as $key => $field) {
621 $params[] = $field['contact_id'];
624 $details = CRM_Utils_Token
::getTokenDetails(
627 $skipOnHold, TRUE, NULL,
628 $mailing->getFlattenedTokens(),
633 $config = CRM_Core_Config
::singleton();
634 foreach ($fields as $key => $field) {
635 $contactID = $field['contact_id'];
636 if (!array_key_exists($contactID, $details[0])) {
637 $details[0][$contactID] = array();
640 // Compose the mailing.
641 $recipient = $replyToEmail = NULL;
642 $replyValue = strcmp($mailing->replyto_email
, $mailing->from_email
);
644 $replyToEmail = $mailing->replyto_email
;
647 $message = $mailing->compose(
648 $this->id
, $field['id'], $field['hash'],
649 $field['contact_id'], $field['email'],
650 $recipient, FALSE, $details[0][$contactID], $attachments,
651 FALSE, NULL, $replyToEmail
653 if (empty($message)) {
654 // lets keep the message in the queue
655 // most likely a permissions related issue with smarty templates
656 // or a bad contact id? CRM-9833
662 $body = &$message->get();
663 $headers = &$message->headers();
665 if ($mailing->sms_provider_id
) {
666 $provider = CRM_SMS_Provider
::singleton(array('mailing_id' => $mailing->id
));
667 $body = $provider->getMessage($message, $field['contact_id'], $details[0][$contactID]);
668 $headers = $provider->getRecipientDetails($field, $details[0][$contactID]);
671 // make $recipient actually be the *encoded* header, so as not to baffle Mail_RFC822, CRM-5743
672 $recipient = $headers['To'];
675 // disable error reporting on real mailings (but leave error reporting for tests), CRM-5744
677 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
680 $result = $mailer->send($recipient, $headers, $body, $this->id
);
686 if (is_a($result, 'PEAR_Error') && !$mailing->sms_provider_id
) {
688 $message = $result->getMessage();
690 strpos($message, 'Failed to write to socket') !== FALSE ||
691 strpos($message, 'Failed to set sender') !== FALSE
693 // lets log this message and code
694 $code = $result->getCode();
695 CRM_Core_Error
::debug_log_message("SMTP Socket Error or failed to set sender error. Message: $message, Code: $code");
697 // these are socket write errors which most likely means smtp connection errors
699 $smtpConnectionErrors++
;
700 if ($smtpConnectionErrors <= 5) {
704 // seems like we have too many of them in a row, we should
705 // write stuff to disk and abort the cron job
713 CRM_Core_Error
::debug_log_message("Too many SMTP Socket Errors. Exiting");
714 CRM_Utils_System
::civiExit();
717 // Register the bounce event.
720 'event_queue_id' => $field['id'],
721 'job_id' => $this->id
,
722 'hash' => $field['hash'],
724 $params = array_merge($params,
725 CRM_Mailing_BAO_BouncePattern
::match($result->getMessage())
727 CRM_Mailing_Event_BAO_Bounce
::create($params);
729 elseif (is_a($result, 'PEAR_Error') && $mailing->sms_provider_id
) {
730 // Handle SMS errors: CRM-15426
731 $job_id = intval($this->id
);
732 $mailing_id = intval($mailing->id
);
733 CRM_Core_Error
::debug_log_message("Failed to send SMS message. Vars: mailing_id: ${mailing_id}, job_id: ${job_id}. Error message follows.");
734 CRM_Core_Error
::debug_log_message($result->getMessage());
737 // Register the delivery event.
738 $deliveredParams[] = $field['id'];
739 $targetParams[] = $field['contact_id'];
742 if ($count % CRM_Mailing_Config
::BULK_MAIL_INSERT_COUNT
== 0) {
751 // hack to stop mailing job at run time, CRM-4246.
752 // to avoid making too many DB calls for this rare case
753 // lets do it when we snapshot
754 $status = CRM_Core_DAO
::getFieldValue(
755 'CRM_Mailing_DAO_MailingJob',
762 if ($status != 'Running') {
770 // seems like a successful delivery or bounce, lets decrement error count
771 // only if we have smtp connection errors
772 if ($smtpConnectionErrors > 0) {
773 $smtpConnectionErrors--;
776 // If we have enabled the Throttle option, this is the time to enforce it.
777 $mailThrottleTime = Civi
::settings()->get('mailThrottleTime');
778 if (!empty($mailThrottleTime)) {
779 usleep((int ) $mailThrottleTime);
783 $result = $this->writeToDB(
796 * @param int $mailingId
797 * The id of the mailing to be canceled.
799 public static function cancel($mailingId) {
802 FROM civicrm_mailing_job
803 WHERE mailing_id = %1
805 AND ( ( job_type IS NULL ) OR
806 job_type <> 'child' )
808 $params = array(1 => array($mailingId, 'Integer'));
809 $job = CRM_Core_DAO
::executeQuery($sql, $params);
811 in_array($job->status
, array('Scheduled', 'Running', 'Paused'))
814 $newJob = new CRM_Mailing_BAO_MailingJob();
815 $newJob->id
= $job->id
;
816 $newJob->end_date
= date('YmdHis');
817 $newJob->status
= 'Canceled';
820 // also cancel all child jobs
822 UPDATE civicrm_mailing_job
823 SET status = 'Canceled',
827 AND job_type = 'child'
828 AND status IN ( 'Scheduled', 'Running', 'Paused' )
831 1 => array($job->id
, 'Integer'),
832 2 => array(date('YmdHis'), 'Timestamp'),
834 CRM_Core_DAO
::executeQuery($sql, $params);
836 CRM_Core_Session
::setStatus(ts('The mailing has been canceled.'), ts('Canceled'), 'success');
841 * Return a translated status enum string.
843 * @param string $status
847 * The translated version
849 public static function status($status) {
850 static $translation = NULL;
852 if (empty($translation)) {
853 $translation = array(
854 'Scheduled' => ts('Scheduled'),
855 'Running' => ts('Running'),
856 'Complete' => ts('Complete'),
857 'Paused' => ts('Paused'),
858 'Canceled' => ts('Canceled'),
861 return CRM_Utils_Array
::value($status, $translation, ts('Not scheduled'));
865 * Return a workflow clause for use in SQL queries,
866 * to only process jobs that are approved.
869 * For use in a WHERE clause
871 public static function workflowClause() {
872 // add an additional check and only process
873 // jobs that are approved
874 if (CRM_Mailing_Info
::workflowEnabled()) {
875 $approveOptionID = CRM_Core_OptionGroup
::getValue('mail_approval_status',
879 if ($approveOptionID) {
880 return " AND m.approval_status_id = $approveOptionID ";
887 * @param array $deliveredParams
888 * @param array $targetParams
893 * @throws CRM_Core_Exception
896 public function writeToDB(
902 static $activityTypeID = NULL;
903 static $writeActivity = NULL;
905 if (!empty($deliveredParams)) {
906 CRM_Mailing_Event_BAO_Delivered
::bulkCreate($deliveredParams);
907 $deliveredParams = array();
910 if ($writeActivity === NULL) {
911 $writeActivity = Civi
::settings()->get('write_activity_record');
914 if (!$writeActivity) {
919 if (!empty($targetParams) && !empty($mailing->scheduled_id
)) {
920 if (!$activityTypeID) {
921 if ($mailing->sms_provider_id
) {
922 $mailing->subject
= $mailing->name
;
923 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Mass SMS'
927 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Bulk Email');
929 if (!$activityTypeID) {
930 CRM_Core_Error
::fatal();
935 'source_contact_id' => $mailing->scheduled_id
,
937 'target_contact_id' => array_unique($targetParams),
938 'activity_type_id' => $activityTypeID,
939 'source_record_id' => $this->mailing_id
,
940 'activity_date_time' => $job_date,
941 'subject' => $mailing->subject
,
943 'deleteActivityTarget' => FALSE,
944 'campaign_id' => $mailing->campaign_id
,
947 //check whether activity is already created for this mailing.
948 //if yes then create only target contact record.
951 FROM civicrm_activity
952 WHERE civicrm_activity.activity_type_id = %1
953 AND civicrm_activity.source_record_id = %2
956 $queryParams = array(
957 1 => array($activityTypeID, 'Integer'),
958 2 => array($this->mailing_id
, 'Integer'),
960 $activityID = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
963 $activity['id'] = $activityID;
966 if (CRM_Core_BAO_Email
::isMultipleBulkMail()) {
967 static $targetRecordID = NULL;
968 if (!$targetRecordID) {
969 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
970 $targetRecordID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
973 // make sure we don't attempt to duplicate the target activity
974 foreach ($activity['target_contact_id'] as $key => $targetID) {
977 FROM civicrm_activity_contact
978 WHERE activity_id = $activityID
979 AND contact_id = $targetID
980 AND record_type_id = $targetRecordID
982 if (CRM_Core_DAO
::singleValueQuery($sql)) {
983 unset($activity['target_contact_id'][$key]);
989 if (is_a(CRM_Activity_BAO_Activity
::create($activity), 'CRM_Core_Error')) {
993 $targetParams = array();
1000 * Search the mailing-event queue for a list of pending delivery tasks.
1003 * @param string $medium
1004 * Ex: 'email' or 'sms'.
1006 * @return \CRM_Mailing_Event_BAO_Queue
1007 * A query object whose rows provide ('id', 'contact_id', 'hash') and ('email' or 'phone').
1009 public static function findPendingTasks($jobId, $medium) {
1010 $eq = new CRM_Mailing_Event_BAO_Queue();
1011 $queueTable = CRM_Mailing_Event_BAO_Queue
::getTableName();
1012 $emailTable = CRM_Core_BAO_Email
::getTableName();
1013 $phoneTable = CRM_Core_BAO_Phone
::getTableName();
1014 $contactTable = CRM_Contact_BAO_Contact
::getTableName();
1015 $deliveredTable = CRM_Mailing_Event_BAO_Delivered
::getTableName();
1016 $bounceTable = CRM_Mailing_Event_BAO_Bounce
::getTableName();
1018 $query = " SELECT $queueTable.id,
1019 $emailTable.email as email,
1020 $queueTable.contact_id,
1024 INNER JOIN $emailTable
1025 ON $queueTable.email_id = $emailTable.id
1026 INNER JOIN $contactTable
1027 ON $contactTable.id = $emailTable.contact_id
1028 LEFT JOIN $deliveredTable
1029 ON $queueTable.id = $deliveredTable.event_queue_id
1030 LEFT JOIN $bounceTable
1031 ON $queueTable.id = $bounceTable.event_queue_id
1032 WHERE $queueTable.job_id = " . $jobId . "
1033 AND $deliveredTable.id IS null
1034 AND $bounceTable.id IS null
1035 AND $contactTable.is_opt_out = 0";
1037 if ($medium === 'sms') {
1039 SELECT $queueTable.id,
1040 $phoneTable.phone as phone,
1041 $queueTable.contact_id,
1045 INNER JOIN $phoneTable
1046 ON $queueTable.phone_id = $phoneTable.id
1047 INNER JOIN $contactTable
1048 ON $contactTable.id = $phoneTable.contact_id
1049 LEFT JOIN $deliveredTable
1050 ON $queueTable.id = $deliveredTable.event_queue_id
1051 LEFT JOIN $bounceTable
1052 ON $queueTable.id = $bounceTable.event_queue_id
1053 WHERE $queueTable.job_id = " . $jobId . "
1054 AND $deliveredTable.id IS null
1055 AND $bounceTable.id IS null
1056 AND ( $contactTable.is_opt_out = 0
1057 OR $contactTable.do_not_sms = 0 )";