3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
36 require_once 'Mail.php';
39 * Class CRM_Mailing_BAO_MailingJob
41 class CRM_Mailing_BAO_MailingJob
extends CRM_Mailing_DAO_MailingJob
{
42 const MAX_CONTACTS_TO_PROCESS
= 1000;
45 * (Dear God Why) Keep a global count of mails processed within the current
51 static $mailsProcessed = 0;
56 public function __construct() {
57 parent
::__construct();
61 * @param array $params
63 * @return CRM_Mailing_BAO_MailingJob
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 $mailing = new CRM_Mailing_BAO_Mailing();
73 $mailing->getRecipients($job->id
, $params['mailing_id'], NULL, NULL, TRUE, FALSE);
78 * Initiate all pending/ready jobs
80 * @param array $testParams
86 public static function runJobs($testParams = NULL, $mode = NULL) {
87 $job = new CRM_Mailing_BAO_MailingJob();
89 $config = CRM_Core_Config
::singleton();
90 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
91 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
93 if (!empty($testParams)) {
97 WHERE id = {$testParams['job_id']}";
101 $currentTime = date('YmdHis');
102 $mailingACL = CRM_Mailing_BAO_Mailing
::mailingACL('m');
103 $domainID = CRM_Core_Config
::domainID();
105 $modeClause = 'AND m.sms_provider_id IS NULL';
106 if ($mode == 'sms') {
107 $modeClause = 'AND m.sms_provider_id IS NOT NULL';
110 // Select the first child job that is scheduled
116 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
119 AND ( ( j.start_date IS null
120 AND j.scheduled_date <= $currentTime
121 AND j.status = 'Scheduled' )
122 OR ( j.status = 'Running'
123 AND j.end_date IS null ) )
124 AND (j.job_type = 'child')
126 ORDER BY j.mailing_id,
134 while ($job->fetch()) {
135 // still use job level lock for each child job
136 $lockName = "civimail.job.{$job->id}";
138 $lock = new CRM_Core_Lock($lockName);
139 if (!$lock->isAcquired()) {
143 // for test jobs we do not change anything, since its on a short-circuit path
144 if (empty($testParams)) {
145 // we've got the lock, but while we were waiting and processing
146 // other emails, this job might have changed under us
147 // lets get the job status again and check
148 $job->status
= CRM_Core_DAO
::getFieldValue(
149 'CRM_Mailing_DAO_MailingJob',
157 $job->status
!= 'Running' &&
158 $job->status
!= 'Scheduled'
160 // this includes Cancelled and other statuses, CRM-4246
166 /* Queue up recipients for the child job being launched */
168 if ($job->status
!= 'Running') {
169 $transaction = new CRM_Core_Transaction();
171 // have to queue it up based on the offset and limits
172 // get the parent ID, and limit and offset
173 $job->queue($testParams);
175 // Mark up the starting time
176 $saveJob = new CRM_Mailing_DAO_MailingJob();
177 $saveJob->id
= $job->id
;
178 $saveJob->start_date
= date('YmdHis');
179 $saveJob->status
= 'Running';
182 $transaction->commit();
186 // make it a persistent connection, CRM-9349
187 if ($mode === NULL) {
188 $mailer = $config->getMailer(TRUE);
190 elseif ($mode == 'sms') {
191 $mailer = CRM_SMS_Provider
::singleton(array('mailing_id' => $job->mailing_id
));
194 // Compose and deliver each child job
195 $isComplete = $job->deliver($mailer, $testParams);
197 CRM_Utils_Hook
::post('create', 'CRM_Mailing_DAO_Spool', $job->id
, $isComplete);
199 // Mark the child complete
203 $transaction = new CRM_Core_Transaction();
205 $saveJob = new CRM_Mailing_DAO_MailingJob();
206 $saveJob->id
= $job->id
;
207 $saveJob->end_date
= date('YmdHis');
208 $saveJob->status
= 'Complete';
211 $transaction->commit();
213 // don't mark the mailing as complete
216 // Release the child joblock
225 // post process to determine if the parent job
226 // as well as the mailing is complete after the run
230 public static function runJobs_post($mode = NULL) {
232 $job = new CRM_Mailing_BAO_MailingJob();
234 $mailing = new CRM_Mailing_BAO_Mailing();
236 $config = CRM_Core_Config
::singleton();
237 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
238 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
240 $currentTime = date('YmdHis');
241 $mailingACL = CRM_Mailing_BAO_Mailing
::mailingACL('m');
242 $domainID = CRM_Core_Config
::domainID();
248 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
250 AND j.scheduled_date <= $currentTime
251 AND j.status = 'Running'
252 AND j.end_date IS null
253 AND (j.job_type != 'child' OR j.job_type is NULL)
254 ORDER BY j.scheduled_date,
259 // For each parent job that is running, let's look at their child jobs
260 while ($job->fetch()) {
262 $child_job = new CRM_Mailing_BAO_MailingJob();
266 FROM civicrm_mailing_job j, civicrm_mailing m
267 WHERE m.id = j.mailing_id
268 AND j.job_type = 'child'
270 AND j.status <> 'Complete'";
271 $params = array(1 => array($job->id
, 'Integer'));
273 $anyChildLeft = CRM_Core_DAO
::singleValueQuery($child_job_sql, $params);
275 // all of the child jobs are complete, update
276 // the parent job as well as the mailing status
277 if (!$anyChildLeft) {
279 $transaction = new CRM_Core_Transaction();
281 $saveJob = new CRM_Mailing_DAO_MailingJob();
282 $saveJob->id
= $job->id
;
283 $saveJob->end_date
= date('YmdHis');
284 $saveJob->status
= 'Complete';
288 $mailing->id
= $job->mailing_id
;
289 $mailing->is_completed
= TRUE;
291 $transaction->commit();
297 // before we run jobs, we need to split the jobs
302 public static function runJobs_pre($offset = 200, $mode = NULL) {
303 $job = new CRM_Mailing_BAO_MailingJob();
305 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
306 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
308 $currentTime = date('YmdHis');
309 $mailingACL = CRM_Mailing_BAO_Mailing
::mailingACL('m');
312 $workflowClause = CRM_Mailing_BAO_MailingJob
::workflowClause();
314 $domainID = CRM_Core_Config
::domainID();
316 $modeClause = 'AND m.sms_provider_id IS NULL';
317 if ($mode == 'sms') {
318 $modeClause = 'AND m.sms_provider_id IS NOT NULL';
321 // Select all the mailing jobs that are created from
322 // when the mailing is submitted or scheduled.
327 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
331 AND ( ( j.start_date IS null
332 AND j.scheduled_date <= $currentTime
333 AND j.status = 'Scheduled'
334 AND j.end_date IS null ) )
335 AND ((j.job_type is NULL) OR (j.job_type <> 'child'))
336 ORDER BY j.scheduled_date,
343 // For each of the "Parent Jobs" we find, we split them into
344 // X Number of child jobs
345 while ($job->fetch()) {
346 // still use job level lock for each child job
347 $lockName = "civimail.job.{$job->id}";
349 $lock = new CRM_Core_Lock($lockName);
350 if (!$lock->isAcquired()) {
354 // Re-fetch the job status in case things
355 // changed between the first query and now
356 // to avoid race conditions
357 $job->status
= CRM_Core_DAO
::getFieldValue(
358 'CRM_Mailing_DAO_MailingJob',
364 if ($job->status
!= 'Scheduled') {
369 $job->split_job($offset);
371 // update the status of the parent job
372 $transaction = new CRM_Core_Transaction();
374 $saveJob = new CRM_Mailing_DAO_MailingJob();
375 $saveJob->id
= $job->id
;
376 $saveJob->start_date
= date('YmdHis');
377 $saveJob->status
= 'Running';
380 $transaction->commit();
382 // Release the job lock
387 // Split the parent job into n number of child job based on an offset
388 // If null or 0 , we create only one child job
392 public function split_job($offset = 200) {
393 $recipient_count = CRM_Mailing_BAO_Recipients
::mailingSize($this->mailing_id
);
395 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
398 $dao = new CRM_Core_DAO();
401 INSERT INTO civicrm_mailing_job
402 (`mailing_id`, `scheduled_date`, `status`, `job_type`, `parent_id`, `job_offset`, `job_limit`)
403 VALUES (%1, %2, %3, %4, %5, %6, %7)
405 $params = array(1 => array($this->mailing_id
, 'Integer'),
406 2 => array($this->scheduled_date
, 'String'),
407 3 => array('Scheduled', 'String'),
408 4 => array('child', 'String'),
409 5 => array($this->id
, 'Integer'),
410 6 => array(0, 'Integer'),
411 7 => array($recipient_count, 'Integer'),
414 // create one child job if the mailing size is less than the offset
415 // probably use a CRM_Mailing_DAO_MailingJob( );
416 if (empty($offset) ||
417 $recipient_count <= $offset
419 CRM_Core_DAO
::executeQuery($sql, $params);
422 // Creating 'child jobs'
423 for ($i = 0; $i < $recipient_count; $i = $i +
$offset) {
425 $params[7][0] = $offset;
426 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 if ($recipients->phone_id
) {
453 $recipients->email_id
= "null";
456 $recipients->phone_id
= "null";
461 $recipients->email_id
,
462 $recipients->contact_id
,
463 $recipients->phone_id
,
466 if ($count % CRM_Core_DAO
::BULK_MAIL_INSERT_COUNT
== 0) {
467 CRM_Mailing_Event_BAO_Queue
::bulkCreate($params, $now);
473 if (!empty($params)) {
474 CRM_Mailing_Event_BAO_Queue
::bulkCreate($params, $now);
482 * @param object $mailer A Mail object to send the messages
484 * @param array $testParams
488 public function deliver(&$mailer, $testParams = NULL) {
489 $mailing = new CRM_Mailing_BAO_Mailing();
490 $mailing->id
= $this->mailing_id
;
491 $mailing->find(TRUE);
494 $eq = new CRM_Mailing_Event_BAO_Queue();
495 $eqTable = CRM_Mailing_Event_BAO_Queue
::getTableName();
496 $emailTable = CRM_Core_BAO_Email
::getTableName();
497 $phoneTable = CRM_Core_DAO_Phone
::getTableName();
498 $contactTable = CRM_Contact_BAO_Contact
::getTableName();
499 $edTable = CRM_Mailing_Event_BAO_Delivered
::getTableName();
500 $ebTable = CRM_Mailing_Event_BAO_Bounce
::getTableName();
502 $query = " SELECT $eqTable.id,
503 $emailTable.email as email,
508 INNER JOIN $emailTable
509 ON $eqTable.email_id = $emailTable.id
510 INNER JOIN $contactTable
511 ON $contactTable.id = $emailTable.contact_id
513 ON $eqTable.id = $edTable.event_queue_id
515 ON $eqTable.id = $ebTable.event_queue_id
516 WHERE $eqTable.job_id = " . $this->id
. "
517 AND $edTable.id IS null
518 AND $ebTable.id IS null
519 AND $contactTable.is_opt_out = 0";
521 if ($mailing->sms_provider_id
) {
524 $phoneTable.phone as phone,
529 INNER JOIN $phoneTable
530 ON $eqTable.phone_id = $phoneTable.id
531 INNER JOIN $contactTable
532 ON $contactTable.id = $phoneTable.contact_id
534 ON $eqTable.id = $edTable.event_queue_id
536 ON $eqTable.id = $ebTable.event_queue_id
537 WHERE $eqTable.job_id = " . $this->id
. "
538 AND $edTable.id IS null
539 AND $ebTable.id IS null
540 AND ( $contactTable.is_opt_out = 0
541 OR $contactTable.do_not_sms = 0 )";
547 if ($config == NULL) {
548 $config = CRM_Core_Config
::singleton();
551 $job_date = CRM_Utils_Date
::isoToMysql($this->scheduled_date
);
554 if (!empty($testParams)) {
555 $mailing->subject
= ts('[CiviMail Draft]') . ' ' . $mailing->subject
;
558 CRM_Mailing_BAO_Mailing
::tokenReplace($mailing);
560 // get and format attachments
561 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_mailing', $mailing->id
);
563 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
564 CRM_Core_Smarty
::registerStringResource();
568 // This handles the edge case scenario where all the mails
569 // have been delivered in prior jobs
572 // make sure that there's no more than $config->mailerBatchLimit mails processed in a run
573 while ($eq->fetch()) {
574 // if ( ( $mailsProcessed % 100 ) == 0 ) {
575 // CRM_Utils_System::xMemory( "$mailsProcessed: " );
579 $config->mailerBatchLimit
> 0 &&
580 self
::$mailsProcessed >= $config->mailerBatchLimit
582 if (!empty($fields)) {
583 $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
588 self
::$mailsProcessed++
;
593 'contact_id' => $eq->contact_id
,
594 'email' => $eq->email
,
595 'phone' => $eq->phone
,
597 if (count($fields) == self
::MAX_CONTACTS_TO_PROCESS
) {
598 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
609 if (!empty($fields)) {
610 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
620 * @param $attachments
625 public function deliverGroup(&$fields, &$mailing, &$mailer, &$job_date, &$attachments) {
626 static $smtpConnectionErrors = 0;
628 if (!is_object($mailer) ||
empty($fields)) {
629 CRM_Core_Error
::fatal();
632 // get the return properties
633 $returnProperties = $mailing->getReturnProperties();
634 $params = $targetParams = $deliveredParams = array();
638 * CRM-15702: Sending bulk sms to contacts without e-mail addres fails.
639 * Solution is to skip checking for on hold
641 $skipOnHold = true; //do include a statement to check wether e-mail address is on hold
642 if ($mailing->sms_provider_id
) {
643 $skipOnHold = false; //do not include a statement to check wether e-mail address is on hold
646 foreach ($fields as $key => $field) {
647 $params[] = $field['contact_id'];
650 $details = CRM_Utils_Token
::getTokenDetails(
653 $skipOnHold, TRUE, NULL,
654 $mailing->getFlattenedTokens(),
659 $config = CRM_Core_Config
::singleton();
660 foreach ($fields as $key => $field) {
661 $contactID = $field['contact_id'];
662 if (!array_key_exists($contactID, $details[0])) {
663 $details[0][$contactID] = array();
666 /* Compose the mailing */
667 $recipient = $replyToEmail = NULL;
668 $replyValue = strcmp($mailing->replyto_email
, $mailing->from_email
);
670 $replyToEmail = $mailing->replyto_email
;
673 $message = &$mailing->compose(
674 $this->id
, $field['id'], $field['hash'],
675 $field['contact_id'], $field['email'],
676 $recipient, FALSE, $details[0][$contactID], $attachments,
677 FALSE, NULL, $replyToEmail
679 if (empty($message)) {
680 // lets keep the message in the queue
681 // most likely a permissions related issue with smarty templates
682 // or a bad contact id? CRM-9833
686 /* Send the mailing */
688 $body = &$message->get();
689 $headers = &$message->headers();
691 if ($mailing->sms_provider_id
) {
692 $provider = CRM_SMS_Provider
::singleton(array('mailing_id' => $mailing->id
));
693 $body = $provider->getMessage($message, $field['contact_id'], $details[0][$contactID]);
694 $headers = $provider->getRecipientDetails($field, $details[0][$contactID]);
697 // make $recipient actually be the *encoded* header, so as not to baffle Mail_RFC822, CRM-5743
698 $recipient = $headers['To'];
701 // disable error reporting on real mailings (but leave error reporting for tests), CRM-5744
703 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
706 $result = $mailer->send($recipient, $headers, $body, $this->id
);
712 if (is_a($result, 'PEAR_Error') && !$mailing->sms_provider_id
) {
714 $message = $result->getMessage();
716 strpos($message, 'Failed to write to socket') !== FALSE ||
717 strpos($message, 'Failed to set sender') !== FALSE
719 // lets log this message and code
720 $code = $result->getCode();
721 CRM_Core_Error
::debug_log_message("SMTP Socket Error or failed to set sender error. Message: $message, Code: $code");
723 // these are socket write errors which most likely means smtp connection errors
725 $smtpConnectionErrors++
;
726 if ($smtpConnectionErrors <= 5) {
730 // seems like we have too many of them in a row, we should
731 // write stuff to disk and abort the cron job
739 CRM_Core_Error
::debug_log_message("Too many SMTP Socket Errors. Exiting");
740 CRM_Utils_System
::civiExit();
743 /* Register the bounce event */
746 'event_queue_id' => $field['id'],
747 'job_id' => $this->id
,
748 'hash' => $field['hash'],
750 $params = array_merge($params,
751 CRM_Mailing_BAO_BouncePattern
::match($result->getMessage())
753 CRM_Mailing_Event_BAO_Bounce
::create($params);
755 elseif (is_a($result, 'PEAR_Error') && $mailing->sms_provider_id
) {
756 // Handle SMS errors: CRM-15426
757 $job_id = intval($this->id
);
758 $mailing_id = intval($mailing->id
);
759 CRM_Core_Error
::debug_log_message("Failed to send SMS message. Vars: mailing_id: ${mailing_id}, job_id: ${job_id}. Error message follows.");
760 CRM_Core_Error
::debug_log_message($result->getMessage());
763 /* Register the delivery event */
764 $deliveredParams[] = $field['id'];
765 $targetParams[] = $field['contact_id'];
768 if ($count % CRM_Core_DAO
::BULK_MAIL_INSERT_COUNT
== 0) {
777 // hack to stop mailing job at run time, CRM-4246.
778 // to avoid making too many DB calls for this rare case
779 // lets do it when we snapshot
780 $status = CRM_Core_DAO
::getFieldValue(
781 'CRM_Mailing_DAO_MailingJob',
788 if ($status != 'Running') {
796 // seems like a successful delivery or bounce, lets decrement error count
797 // only if we have smtp connection errors
798 if ($smtpConnectionErrors > 0) {
799 $smtpConnectionErrors--;
802 // If we have enabled the Throttle option, this is the time to enforce it.
803 if (isset($config->mailThrottleTime
) && $config->mailThrottleTime
> 0) {
804 usleep((int ) $config->mailThrottleTime
);
808 $result = $this->writeToDB(
821 * @param int $mailingId the id of the mailing to be canceled
824 public static function cancel($mailingId) {
827 FROM civicrm_mailing_job
828 WHERE mailing_id = %1
830 AND ( ( job_type IS NULL ) OR
831 job_type <> 'child' )
833 $params = array(1 => array($mailingId, 'Integer'));
834 $job = CRM_Core_DAO
::executeQuery($sql, $params);
836 in_array($job->status
, array('Scheduled', 'Running', 'Paused'))
839 $newJob = new CRM_Mailing_BAO_MailingJob();
840 $newJob->id
= $job->id
;
841 $newJob->end_date
= date('YmdHis');
842 $newJob->status
= 'Canceled';
845 // also cancel all child jobs
847 UPDATE civicrm_mailing_job
848 SET status = 'Canceled',
852 AND job_type = 'child'
853 AND status IN ( 'Scheduled', 'Running', 'Paused' )
855 $params = array(1 => array($job->id
, 'Integer'),
856 2 => array(date('YmdHis'), 'Timestamp'),
858 CRM_Core_DAO
::executeQuery($sql, $params);
860 CRM_Core_Session
::setStatus(ts('The mailing has been canceled.'), ts('Canceled'), 'success');
865 * Return a translated status enum string
867 * @param string $status The status enum
869 * @return string The translated version
872 public static function status($status) {
873 static $translation = NULL;
875 if (empty($translation)) {
876 $translation = array(
877 'Scheduled' => ts('Scheduled'),
878 'Running' => ts('Running'),
879 'Complete' => ts('Complete'),
880 'Paused' => ts('Paused'),
881 'Canceled' => ts('Canceled'),
884 return CRM_Utils_Array
::value($status, $translation, ts('Not scheduled'));
888 * Return a workflow clause for use in SQL queries,
889 * to only process jobs that are approved.
891 * @return string For use in a WHERE clause
894 public static function workflowClause() {
895 // add an additional check and only process
896 // jobs that are approved
897 if (CRM_Mailing_Info
::workflowEnabled()) {
898 $approveOptionID = CRM_Core_OptionGroup
::getValue('mail_approval_status',
902 if ($approveOptionID) {
903 return " AND m.approval_status_id = $approveOptionID ";
910 * @param array $deliveredParams
911 * @param array $targetParams
916 * @throws CRM_Core_Exception
919 public function writeToDB(
925 static $activityTypeID = NULL;
926 static $writeActivity = NULL;
928 if (!empty($deliveredParams)) {
929 CRM_Mailing_Event_BAO_Delivered
::bulkCreate($deliveredParams);
930 $deliveredParams = array();
933 if ($writeActivity === NULL) {
934 $writeActivity = CRM_Core_BAO_Setting
::getItem(
935 CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
936 'write_activity_record',
942 if (!$writeActivity) {
947 if (!empty($targetParams) && !empty($mailing->scheduled_id
)) {
948 if (!$activityTypeID) {
949 if ($mailing->sms_provider_id
) {
950 $mailing->subject
= $mailing->name
;
951 $activityTypeID = CRM_Core_OptionGroup
::getValue(
958 $activityTypeID = CRM_Core_OptionGroup
::getValue(
964 if (!$activityTypeID) {
965 CRM_Core_Error
::fatal();
970 'source_contact_id' => $mailing->scheduled_id
,
972 'target_contact_id' => array_unique($targetParams),
973 'activity_type_id' => $activityTypeID,
974 'source_record_id' => $this->mailing_id
,
975 'activity_date_time' => $job_date,
976 'subject' => $mailing->subject
,
978 'deleteActivityTarget' => FALSE,
979 'campaign_id' => $mailing->campaign_id
,
982 //check whether activity is already created for this mailing.
983 //if yes then create only target contact record.
986 FROM civicrm_activity
987 WHERE civicrm_activity.activity_type_id = %1
988 AND civicrm_activity.source_record_id = %2
991 $queryParams = array(
992 1 => array($activityTypeID, 'Integer'),
993 2 => array($this->mailing_id
, 'Integer'),
995 $activityID = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
998 $activity['id'] = $activityID;
1001 if (CRM_Core_BAO_Email
::isMultipleBulkMail()) {
1002 static $targetRecordID = NULL;
1003 if (!$targetRecordID) {
1004 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1005 $targetRecordID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1008 // make sure we don't attempt to duplicate the target activity
1009 foreach ($activity['target_contact_id'] as $key => $targetID) {
1012 FROM civicrm_activity_contact
1013 WHERE activity_id = $activityID
1014 AND contact_id = $targetID
1015 AND record_type_id = $targetRecordID
1017 if (CRM_Core_DAO
::singleValueQuery($sql)) {
1018 unset($activity['target_contact_id'][$key]);
1024 if (is_a(CRM_Activity_BAO_Activity
::create($activity), 'CRM_Core_Error')) {
1028 $targetParams = array();