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 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
87 public static function runJobs($testParams = NULL, $mode = NULL) {
88 $job = new CRM_Mailing_BAO_MailingJob();
90 $config = CRM_Core_Config
::singleton();
91 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
92 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
94 if (!empty($testParams)) {
98 WHERE id = {$testParams['job_id']}";
102 $currentTime = date('YmdHis');
103 $mailingACL = CRM_Mailing_BAO_Mailing
::mailingACL('m');
104 $domainID = CRM_Core_Config
::domainID();
106 $modeClause = 'AND m.sms_provider_id IS NULL';
107 if ($mode == 'sms') {
108 $modeClause = 'AND m.sms_provider_id IS NOT NULL';
111 // Select the first child job that is scheduled
117 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
120 AND ( ( j.start_date IS null
121 AND j.scheduled_date <= $currentTime
122 AND j.status = 'Scheduled' )
123 OR ( j.status = 'Running'
124 AND j.end_date IS null ) )
125 AND (j.job_type = 'child')
127 ORDER BY j.mailing_id,
135 while ($job->fetch()) {
136 // still use job level lock for each child job
137 $lockName = "civimail.job.{$job->id}";
139 $lock = new CRM_Core_Lock($lockName);
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 // make it a persistent connection, CRM-9349
188 if ($mode === NULL) {
189 $mailer = $config->getMailer(TRUE);
191 elseif ($mode == 'sms') {
192 $mailer = CRM_SMS_Provider
::singleton(array('mailing_id' => $job->mailing_id
));
195 // Compose and deliver each child job
196 $isComplete = $job->deliver($mailer, $testParams);
198 CRM_Utils_Hook
::post('create', 'CRM_Mailing_DAO_Spool', $job->id
, $isComplete);
200 // Mark the child complete
204 $transaction = new CRM_Core_Transaction();
206 $saveJob = new CRM_Mailing_DAO_MailingJob();
207 $saveJob->id
= $job->id
;
208 $saveJob->end_date
= date('YmdHis');
209 $saveJob->status
= 'Complete';
212 $transaction->commit();
214 // don't mark the mailing as complete
217 // Release the child joblock
226 // post process to determine if the parent job
227 // as well as the mailing is complete after the run
231 public static function runJobs_post($mode = NULL) {
233 $job = new CRM_Mailing_BAO_MailingJob();
235 $mailing = new CRM_Mailing_BAO_Mailing();
237 $config = CRM_Core_Config
::singleton();
238 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
239 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
241 $currentTime = date('YmdHis');
242 $mailingACL = CRM_Mailing_BAO_Mailing
::mailingACL('m');
243 $domainID = CRM_Core_Config
::domainID();
249 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
251 AND j.scheduled_date <= $currentTime
252 AND j.status = 'Running'
253 AND j.end_date IS null
254 AND (j.job_type != 'child' OR j.job_type is NULL)
255 ORDER BY j.scheduled_date,
260 // For each parent job that is running, let's look at their child jobs
261 while ($job->fetch()) {
263 $child_job = new CRM_Mailing_BAO_MailingJob();
267 FROM civicrm_mailing_job j, civicrm_mailing m
268 WHERE m.id = j.mailing_id
269 AND j.job_type = 'child'
271 AND j.status <> 'Complete'";
272 $params = array(1 => array($job->id
, 'Integer'));
274 $anyChildLeft = CRM_Core_DAO
::singleValueQuery($child_job_sql, $params);
276 // all of the child jobs are complete, update
277 // the parent job as well as the mailing status
278 if (!$anyChildLeft) {
280 $transaction = new CRM_Core_Transaction();
282 $saveJob = new CRM_Mailing_DAO_MailingJob();
283 $saveJob->id
= $job->id
;
284 $saveJob->end_date
= date('YmdHis');
285 $saveJob->status
= 'Complete';
289 $mailing->id
= $job->mailing_id
;
290 $mailing->is_completed
= TRUE;
292 $transaction->commit();
298 // before we run jobs, we need to split the jobs
303 public static function runJobs_pre($offset = 200, $mode = NULL) {
304 $job = new CRM_Mailing_BAO_MailingJob();
306 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
307 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
309 $currentTime = date('YmdHis');
310 $mailingACL = CRM_Mailing_BAO_Mailing
::mailingACL('m');
313 $workflowClause = CRM_Mailing_BAO_MailingJob
::workflowClause();
315 $domainID = CRM_Core_Config
::domainID();
317 $modeClause = 'AND m.sms_provider_id IS NULL';
318 if ($mode == 'sms') {
319 $modeClause = 'AND m.sms_provider_id IS NOT NULL';
322 // Select all the mailing jobs that are created from
323 // when the mailing is submitted or scheduled.
328 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
332 AND ( ( j.start_date IS null
333 AND j.scheduled_date <= $currentTime
334 AND j.status = 'Scheduled'
335 AND j.end_date IS null ) )
336 AND ((j.job_type is NULL) OR (j.job_type <> 'child'))
337 ORDER BY j.scheduled_date,
344 // For each of the "Parent Jobs" we find, we split them into
345 // X Number of child jobs
346 while ($job->fetch()) {
347 // still use job level lock for each child job
348 $lockName = "civimail.job.{$job->id}";
350 $lock = new CRM_Core_Lock($lockName);
351 if (!$lock->isAcquired()) {
355 // Re-fetch the job status in case things
356 // changed between the first query and now
357 // to avoid race conditions
358 $job->status
= CRM_Core_DAO
::getFieldValue(
359 'CRM_Mailing_DAO_MailingJob',
365 if ($job->status
!= 'Scheduled') {
370 $job->split_job($offset);
372 // update the status of the parent job
373 $transaction = new CRM_Core_Transaction();
375 $saveJob = new CRM_Mailing_DAO_MailingJob();
376 $saveJob->id
= $job->id
;
377 $saveJob->start_date
= date('YmdHis');
378 $saveJob->status
= 'Running';
381 $transaction->commit();
383 // Release the job lock
388 // Split the parent job into n number of child job based on an offset
389 // If null or 0 , we create only one child job
393 public function split_job($offset = 200) {
394 $recipient_count = CRM_Mailing_BAO_Recipients
::mailingSize($this->mailing_id
);
396 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
399 $dao = new CRM_Core_DAO();
402 INSERT INTO civicrm_mailing_job
403 (`mailing_id`, `scheduled_date`, `status`, `job_type`, `parent_id`, `job_offset`, `job_limit`)
404 VALUES (%1, %2, %3, %4, %5, %6, %7)
406 $params = array(1 => array($this->mailing_id
, 'Integer'),
407 2 => array($this->scheduled_date
, 'String'),
408 3 => array('Scheduled', 'String'),
409 4 => array('child', 'String'),
410 5 => array($this->id
, 'Integer'),
411 6 => array(0, 'Integer'),
412 7 => array($recipient_count, 'Integer'),
415 // create one child job if the mailing size is less than the offset
416 // probably use a CRM_Mailing_DAO_MailingJob( );
417 if (empty($offset) ||
418 $recipient_count <= $offset
420 CRM_Core_DAO
::executeQuery($sql, $params);
423 // Creating 'child jobs'
424 for ($i = 0; $i < $recipient_count; $i = $i +
$offset) {
426 $params[7][0] = $offset;
427 CRM_Core_DAO
::executeQuery($sql, $params);
433 * @param array $testParams
435 public function queue($testParams = NULL) {
436 $mailing = new CRM_Mailing_BAO_Mailing();
437 $mailing->id
= $this->mailing_id
;
438 if (!empty($testParams)) {
439 $mailing->getTestRecipients($testParams);
442 // We are still getting all the recipients from the parent job
443 // so we don't mess with the include/exclude logic.
444 $recipients = CRM_Mailing_BAO_Recipients
::mailingQuery($this->mailing_id
, $this->job_offset
, $this->job_limit
);
446 // FIXME: this is not very smart, we should move this to one DB call
447 // INSERT INTO ... SELECT FROM ..
448 // the thing we need to figure out is how to generate the hash automatically
452 while ($recipients->fetch()) {
453 if ($recipients->phone_id
) {
454 $recipients->email_id
= "null";
457 $recipients->phone_id
= "null";
462 $recipients->email_id
,
463 $recipients->contact_id
,
464 $recipients->phone_id
,
467 if ($count % CRM_Core_DAO
::BULK_MAIL_INSERT_COUNT
== 0) {
468 CRM_Mailing_Event_BAO_Queue
::bulkCreate($params, $now);
474 if (!empty($params)) {
475 CRM_Mailing_Event_BAO_Queue
::bulkCreate($params, $now);
483 * @param object $mailer A Mail object to send the messages
485 * @param array $testParams
490 public function deliver(&$mailer, $testParams = NULL) {
491 $mailing = new CRM_Mailing_BAO_Mailing();
492 $mailing->id
= $this->mailing_id
;
493 $mailing->find(TRUE);
496 $eq = new CRM_Mailing_Event_BAO_Queue();
497 $eqTable = CRM_Mailing_Event_BAO_Queue
::getTableName();
498 $emailTable = CRM_Core_BAO_Email
::getTableName();
499 $phoneTable = CRM_Core_DAO_Phone
::getTableName();
500 $contactTable = CRM_Contact_BAO_Contact
::getTableName();
501 $edTable = CRM_Mailing_Event_BAO_Delivered
::getTableName();
502 $ebTable = CRM_Mailing_Event_BAO_Bounce
::getTableName();
504 $query = " SELECT $eqTable.id,
505 $emailTable.email as email,
510 INNER JOIN $emailTable
511 ON $eqTable.email_id = $emailTable.id
512 INNER JOIN $contactTable
513 ON $contactTable.id = $emailTable.contact_id
515 ON $eqTable.id = $edTable.event_queue_id
517 ON $eqTable.id = $ebTable.event_queue_id
518 WHERE $eqTable.job_id = " . $this->id
. "
519 AND $edTable.id IS null
520 AND $ebTable.id IS null
521 AND $contactTable.is_opt_out = 0";
523 if ($mailing->sms_provider_id
) {
526 $phoneTable.phone as phone,
531 INNER JOIN $phoneTable
532 ON $eqTable.phone_id = $phoneTable.id
533 INNER JOIN $contactTable
534 ON $contactTable.id = $phoneTable.contact_id
536 ON $eqTable.id = $edTable.event_queue_id
538 ON $eqTable.id = $ebTable.event_queue_id
539 WHERE $eqTable.job_id = " . $this->id
. "
540 AND $edTable.id IS null
541 AND $ebTable.id IS null
542 AND ( $contactTable.is_opt_out = 0
543 OR $contactTable.do_not_sms = 0 )";
549 if ($config == NULL) {
550 $config = CRM_Core_Config
::singleton();
553 $job_date = CRM_Utils_Date
::isoToMysql($this->scheduled_date
);
556 if (!empty($testParams)) {
557 $mailing->subject
= ts('[CiviMail Draft]') . ' ' . $mailing->subject
;
560 CRM_Mailing_BAO_Mailing
::tokenReplace($mailing);
562 // get and format attachments
563 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_mailing', $mailing->id
);
565 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
566 CRM_Core_Smarty
::registerStringResource();
570 // This handles the edge case scenario where all the mails
571 // have been delivered in prior jobs
574 // make sure that there's no more than $config->mailerBatchLimit mails processed in a run
575 while ($eq->fetch()) {
576 // if ( ( $mailsProcessed % 100 ) == 0 ) {
577 // CRM_Utils_System::xMemory( "$mailsProcessed: " );
581 $config->mailerBatchLimit
> 0 &&
582 self
::$mailsProcessed >= $config->mailerBatchLimit
584 if (!empty($fields)) {
585 $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
590 self
::$mailsProcessed++
;
595 'contact_id' => $eq->contact_id
,
596 'email' => $eq->email
,
597 'phone' => $eq->phone
,
599 if (count($fields) == self
::MAX_CONTACTS_TO_PROCESS
) {
600 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
611 if (!empty($fields)) {
612 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
622 * @param $attachments
627 public function deliverGroup(&$fields, &$mailing, &$mailer, &$job_date, &$attachments) {
628 static $smtpConnectionErrors = 0;
630 if (!is_object($mailer) ||
empty($fields)) {
631 CRM_Core_Error
::fatal();
634 // get the return properties
635 $returnProperties = $mailing->getReturnProperties();
636 $params = $targetParams = $deliveredParams = array();
640 * CRM-15702: Sending bulk sms to contacts without e-mail addres fails.
641 * Solution is to skip checking for on hold
643 $skipOnHold = true; //do include a statement to check wether e-mail address is on hold
644 if ($mailing->sms_provider_id
) {
645 $skipOnHold = false; //do not include a statement to check wether e-mail address is on hold
648 foreach ($fields as $key => $field) {
649 $params[] = $field['contact_id'];
652 $details = CRM_Utils_Token
::getTokenDetails(
655 $skipOnHold, TRUE, NULL,
656 $mailing->getFlattenedTokens(),
661 $config = CRM_Core_Config
::singleton();
662 foreach ($fields as $key => $field) {
663 $contactID = $field['contact_id'];
664 if (!array_key_exists($contactID, $details[0])) {
665 $details[0][$contactID] = array();
668 /* Compose the mailing */
669 $recipient = $replyToEmail = NULL;
670 $replyValue = strcmp($mailing->replyto_email
, $mailing->from_email
);
672 $replyToEmail = $mailing->replyto_email
;
675 $message = &$mailing->compose(
676 $this->id
, $field['id'], $field['hash'],
677 $field['contact_id'], $field['email'],
678 $recipient, FALSE, $details[0][$contactID], $attachments,
679 FALSE, NULL, $replyToEmail
681 if (empty($message)) {
682 // lets keep the message in the queue
683 // most likely a permissions related issue with smarty templates
684 // or a bad contact id? CRM-9833
688 /* Send the mailing */
690 $body = &$message->get();
691 $headers = &$message->headers();
693 if ($mailing->sms_provider_id
) {
694 $provider = CRM_SMS_Provider
::singleton(array('mailing_id' => $mailing->id
));
695 $body = $provider->getMessage($message, $field['contact_id'], $details[0][$contactID]);
696 $headers = $provider->getRecipientDetails($field, $details[0][$contactID]);
699 // make $recipient actually be the *encoded* header, so as not to baffle Mail_RFC822, CRM-5743
700 $recipient = $headers['To'];
703 // disable error reporting on real mailings (but leave error reporting for tests), CRM-5744
705 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
708 $result = $mailer->send($recipient, $headers, $body, $this->id
);
714 if (is_a($result, 'PEAR_Error') && !$mailing->sms_provider_id
) {
716 $message = $result->getMessage();
718 strpos($message, 'Failed to write to socket') !== FALSE ||
719 strpos($message, 'Failed to set sender') !== FALSE
721 // lets log this message and code
722 $code = $result->getCode();
723 CRM_Core_Error
::debug_log_message("SMTP Socket Error or failed to set sender error. Message: $message, Code: $code");
725 // these are socket write errors which most likely means smtp connection errors
727 $smtpConnectionErrors++
;
728 if ($smtpConnectionErrors <= 5) {
732 // seems like we have too many of them in a row, we should
733 // write stuff to disk and abort the cron job
741 CRM_Core_Error
::debug_log_message("Too many SMTP Socket Errors. Exiting");
742 CRM_Utils_System
::civiExit();
745 /* Register the bounce event */
748 'event_queue_id' => $field['id'],
749 'job_id' => $this->id
,
750 'hash' => $field['hash'],
752 $params = array_merge($params,
753 CRM_Mailing_BAO_BouncePattern
::match($result->getMessage())
755 CRM_Mailing_Event_BAO_Bounce
::create($params);
757 elseif (is_a($result, 'PEAR_Error') && $mailing->sms_provider_id
) {
758 // Handle SMS errors: CRM-15426
759 $job_id = intval($this->id
);
760 $mailing_id = intval($mailing->id
);
761 CRM_Core_Error
::debug_log_message("Failed to send SMS message. Vars: mailing_id: ${mailing_id}, job_id: ${job_id}. Error message follows.");
762 CRM_Core_Error
::debug_log_message($result->getMessage());
765 /* Register the delivery event */
766 $deliveredParams[] = $field['id'];
767 $targetParams[] = $field['contact_id'];
770 if ($count % CRM_Core_DAO
::BULK_MAIL_INSERT_COUNT
== 0) {
779 // hack to stop mailing job at run time, CRM-4246.
780 // to avoid making too many DB calls for this rare case
781 // lets do it when we snapshot
782 $status = CRM_Core_DAO
::getFieldValue(
783 'CRM_Mailing_DAO_MailingJob',
790 if ($status != 'Running') {
798 // seems like a successful delivery or bounce, lets decrement error count
799 // only if we have smtp connection errors
800 if ($smtpConnectionErrors > 0) {
801 $smtpConnectionErrors--;
804 // If we have enabled the Throttle option, this is the time to enforce it.
805 if (isset($config->mailThrottleTime
) && $config->mailThrottleTime
> 0) {
806 usleep((int ) $config->mailThrottleTime
);
810 $result = $this->writeToDB(
823 * @param int $mailingId the id of the mailing to be canceled
826 public static function cancel($mailingId) {
829 FROM civicrm_mailing_job
830 WHERE mailing_id = %1
832 AND ( ( job_type IS NULL ) OR
833 job_type <> 'child' )
835 $params = array(1 => array($mailingId, 'Integer'));
836 $job = CRM_Core_DAO
::executeQuery($sql, $params);
838 in_array($job->status
, array('Scheduled', 'Running', 'Paused'))
841 $newJob = new CRM_Mailing_BAO_MailingJob();
842 $newJob->id
= $job->id
;
843 $newJob->end_date
= date('YmdHis');
844 $newJob->status
= 'Canceled';
847 // also cancel all child jobs
849 UPDATE civicrm_mailing_job
850 SET status = 'Canceled',
854 AND job_type = 'child'
855 AND status IN ( 'Scheduled', 'Running', 'Paused' )
857 $params = array(1 => array($job->id
, 'Integer'),
858 2 => array(date('YmdHis'), 'Timestamp'),
860 CRM_Core_DAO
::executeQuery($sql, $params);
862 CRM_Core_Session
::setStatus(ts('The mailing has been canceled.'), ts('Canceled'), 'success');
867 * Return a translated status enum string
869 * @param string $status The status enum
871 * @return string The translated version
875 public static function status($status) {
876 static $translation = NULL;
878 if (empty($translation)) {
879 $translation = array(
880 'Scheduled' => ts('Scheduled'),
881 'Running' => ts('Running'),
882 'Complete' => ts('Complete'),
883 'Paused' => ts('Paused'),
884 'Canceled' => ts('Canceled'),
887 return CRM_Utils_Array
::value($status, $translation, ts('Not scheduled'));
891 * Return a workflow clause for use in SQL queries,
892 * to only process jobs that are approved.
894 * @return string For use in a WHERE clause
898 public static function workflowClause() {
899 // add an additional check and only process
900 // jobs that are approved
901 if (CRM_Mailing_Info
::workflowEnabled()) {
902 $approveOptionID = CRM_Core_OptionGroup
::getValue('mail_approval_status',
906 if ($approveOptionID) {
907 return " AND m.approval_status_id = $approveOptionID ";
914 * @param array $deliveredParams
915 * @param array $targetParams
920 * @throws CRM_Core_Exception
923 public function writeToDB(
929 static $activityTypeID = NULL;
930 static $writeActivity = NULL;
932 if (!empty($deliveredParams)) {
933 CRM_Mailing_Event_BAO_Delivered
::bulkCreate($deliveredParams);
934 $deliveredParams = array();
937 if ($writeActivity === NULL) {
938 $writeActivity = CRM_Core_BAO_Setting
::getItem(
939 CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
940 'write_activity_record',
946 if (!$writeActivity) {
951 if (!empty($targetParams) && !empty($mailing->scheduled_id
)) {
952 if (!$activityTypeID) {
953 if ($mailing->sms_provider_id
) {
954 $mailing->subject
= $mailing->name
;
955 $activityTypeID = CRM_Core_OptionGroup
::getValue(
962 $activityTypeID = CRM_Core_OptionGroup
::getValue(
968 if (!$activityTypeID) {
969 CRM_Core_Error
::fatal();
974 'source_contact_id' => $mailing->scheduled_id
,
976 'target_contact_id' => array_unique($targetParams),
977 'activity_type_id' => $activityTypeID,
978 'source_record_id' => $this->mailing_id
,
979 'activity_date_time' => $job_date,
980 'subject' => $mailing->subject
,
982 'deleteActivityTarget' => FALSE,
983 'campaign_id' => $mailing->campaign_id
,
986 //check whether activity is already created for this mailing.
987 //if yes then create only target contact record.
990 FROM civicrm_activity
991 WHERE civicrm_activity.activity_type_id = %1
992 AND civicrm_activity.source_record_id = %2
995 $queryParams = array(
996 1 => array($activityTypeID, 'Integer'),
997 2 => array($this->mailing_id
, 'Integer'),
999 $activityID = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
1002 $activity['id'] = $activityID;
1005 if (CRM_Core_BAO_Email
::isMultipleBulkMail()) {
1006 static $targetRecordID = NULL;
1007 if (!$targetRecordID) {
1008 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1009 $targetRecordID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1012 // make sure we don't attempt to duplicate the target activity
1013 foreach ($activity['target_contact_id'] as $key => $targetID) {
1016 FROM civicrm_activity_contact
1017 WHERE activity_id = $activityID
1018 AND contact_id = $targetID
1019 AND record_type_id = $targetRecordID
1021 if (CRM_Core_DAO
::singleValueQuery($sql)) {
1022 unset($activity['target_contact_id'][$key]);
1028 if (is_a(CRM_Activity_BAO_Activity
::create($activity), 'CRM_Core_Error')) {
1032 $targetParams = array();