3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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();
58 * @param array $params
60 * @return CRM_Mailing_BAO_MailingJob
62 static public function create($params) {
63 $job = new CRM_Mailing_BAO_MailingJob();
64 $job->mailing_id
= $params['mailing_id'];
65 $job->status
= $params['status'];
66 $job->scheduled_date
= $params['scheduled_date'];
67 $job->is_test
= $params['is_test'];
69 $mailing = new CRM_Mailing_BAO_Mailing();
70 $mailing->id
= $params['mailing_id'];
71 if ($mailing->id
&& $mailing->find(TRUE)) {
72 $mailing->getRecipients($job->id
, $params['mailing_id'], TRUE, $mailing->dedupe_email
);
76 throw new CRM_Core_Exception("Failed to create job: Unknown mailing ID");
81 * Initiate all pending/ready jobs
83 * @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,
133 while ($job->fetch()) {
134 // still use job level lock for each child job
135 $lock = Civi
::lockManager()->acquire("data.mailing.job.{$job->id}");
136 if (!$lock->isAcquired()) {
140 // for test jobs we do not change anything, since its on a short-circuit path
141 if (empty($testParams)) {
142 // we've got the lock, but while we were waiting and processing
143 // other emails, this job might have changed under us
144 // lets get the job status again and check
145 $job->status
= CRM_Core_DAO
::getFieldValue(
146 'CRM_Mailing_DAO_MailingJob',
154 $job->status
!= 'Running' &&
155 $job->status
!= 'Scheduled'
157 // this includes Cancelled and other statuses, CRM-4246
163 /* Queue up recipients for the child job being launched */
165 if ($job->status
!= 'Running') {
166 $transaction = new CRM_Core_Transaction();
168 // have to queue it up based on the offset and limits
169 // get the parent ID, and limit and offset
170 $job->queue($testParams);
172 // Mark up the starting time
173 $saveJob = new CRM_Mailing_DAO_MailingJob();
174 $saveJob->id
= $job->id
;
175 $saveJob->start_date
= date('YmdHis');
176 $saveJob->status
= 'Running';
179 $transaction->commit();
183 if ($mode === NULL) {
184 $mailer = \Civi
::service('pear_mail');
186 elseif ($mode == 'sms') {
187 $mailer = CRM_SMS_Provider
::singleton(array('mailing_id' => $job->mailing_id
));
190 // Compose and deliver each child job
191 $isComplete = $job->deliver($mailer, $testParams);
193 CRM_Utils_Hook
::post('create', 'CRM_Mailing_DAO_Spool', $job->id
, $isComplete);
195 // Mark the child complete
199 $transaction = new CRM_Core_Transaction();
201 $saveJob = new CRM_Mailing_DAO_MailingJob();
202 $saveJob->id
= $job->id
;
203 $saveJob->end_date
= date('YmdHis');
204 $saveJob->status
= 'Complete';
207 $transaction->commit();
209 // don't mark the mailing as complete
212 // Release the child joblock
222 * Post process to determine if the parent job
223 * as well as the mailing is complete after the run.
226 public static function runJobs_post($mode = NULL) {
228 $job = new CRM_Mailing_BAO_MailingJob();
230 $mailing = new CRM_Mailing_BAO_Mailing();
232 $config = CRM_Core_Config
::singleton();
233 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
234 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
236 $currentTime = date('YmdHis');
237 $mailingACL = CRM_Mailing_BAO_Mailing
::mailingACL('m');
238 $domainID = CRM_Core_Config
::domainID();
244 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
246 AND j.scheduled_date <= $currentTime
247 AND j.status = 'Running'
248 AND j.end_date IS null
249 AND (j.job_type != 'child' OR j.job_type is NULL)
250 ORDER BY j.scheduled_date,
255 // For each parent job that is running, let's look at their child jobs
256 while ($job->fetch()) {
258 $child_job = new CRM_Mailing_BAO_MailingJob();
262 FROM civicrm_mailing_job j, civicrm_mailing m
263 WHERE m.id = j.mailing_id
264 AND j.job_type = 'child'
266 AND j.status <> 'Complete'";
267 $params = array(1 => array($job->id
, 'Integer'));
269 $anyChildLeft = CRM_Core_DAO
::singleValueQuery($child_job_sql, $params);
271 // all of the child jobs are complete, update
272 // the parent job as well as the mailing status
273 if (!$anyChildLeft) {
275 $transaction = new CRM_Core_Transaction();
277 $saveJob = new CRM_Mailing_DAO_MailingJob();
278 $saveJob->id
= $job->id
;
279 $saveJob->end_date
= date('YmdHis');
280 $saveJob->status
= 'Complete';
284 $mailing->id
= $job->mailing_id
;
285 $mailing->is_completed
= TRUE;
287 $transaction->commit();
294 * before we run jobs, we need to split the jobs
298 public static function runJobs_pre($offset = 200, $mode = NULL) {
299 $job = new CRM_Mailing_BAO_MailingJob();
301 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
302 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
304 $currentTime = date('YmdHis');
305 $mailingACL = CRM_Mailing_BAO_Mailing
::mailingACL('m');
307 $workflowClause = CRM_Mailing_BAO_MailingJob
::workflowClause();
309 $domainID = CRM_Core_Config
::domainID();
311 $modeClause = 'AND m.sms_provider_id IS NULL';
312 if ($mode == 'sms') {
313 $modeClause = 'AND m.sms_provider_id IS NOT NULL';
316 // Select all the mailing jobs that are created from
317 // when the mailing is submitted or scheduled.
322 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
326 AND ( ( j.start_date IS null
327 AND j.scheduled_date <= $currentTime
328 AND j.status = 'Scheduled'
329 AND j.end_date IS null ) )
330 AND ((j.job_type is NULL) OR (j.job_type <> 'child'))
331 ORDER BY j.scheduled_date,
336 // For each of the "Parent Jobs" we find, we split them into
337 // X Number of child jobs
338 while ($job->fetch()) {
339 // still use job level lock for each child job
340 $lock = Civi
::lockManager()->acquire("data.mailing.job.{$job->id}");
341 if (!$lock->isAcquired()) {
345 // Re-fetch the job status in case things
346 // changed between the first query and now
347 // to avoid race conditions
348 $job->status
= CRM_Core_DAO
::getFieldValue(
349 'CRM_Mailing_DAO_MailingJob',
355 if ($job->status
!= 'Scheduled') {
360 $job->split_job($offset);
362 // update the status of the parent job
363 $transaction = new CRM_Core_Transaction();
365 $saveJob = new CRM_Mailing_DAO_MailingJob();
366 $saveJob->id
= $job->id
;
367 $saveJob->start_date
= date('YmdHis');
368 $saveJob->status
= 'Running';
371 $transaction->commit();
373 // Release the job lock
379 * Split the parent job into n number of child job based on an offset.
380 * If null or 0 , we create only one child job
383 public function split_job($offset = 200) {
384 $recipient_count = CRM_Mailing_BAO_Recipients
::mailingSize($this->mailing_id
);
386 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
388 $dao = new CRM_Core_DAO();
391 INSERT INTO civicrm_mailing_job
392 (`mailing_id`, `scheduled_date`, `status`, `job_type`, `parent_id`, `job_offset`, `job_limit`)
393 VALUES (%1, %2, %3, %4, %5, %6, %7)
396 1 => array($this->mailing_id
, 'Integer'),
397 2 => array($this->scheduled_date
, 'String'),
398 3 => array('Scheduled', 'String'),
399 4 => array('child', 'String'),
400 5 => array($this->id
, 'Integer'),
401 6 => array(0, 'Integer'),
402 7 => array($recipient_count, 'Integer'),
405 // create one child job if the mailing size is less than the offset
406 // probably use a CRM_Mailing_DAO_MailingJob( );
407 if (empty($offset) ||
408 $recipient_count <= $offset
410 CRM_Core_DAO
::executeQuery($sql, $params);
413 // Creating 'child jobs'
414 for ($i = 0; $i < $recipient_count; $i = $i +
$offset) {
416 $params[7][0] = $offset;
417 CRM_Core_DAO
::executeQuery($sql, $params);
423 * @param array $testParams
425 public function queue($testParams = NULL) {
426 $mailing = new CRM_Mailing_BAO_Mailing();
427 $mailing->id
= $this->mailing_id
;
428 if (!empty($testParams)) {
429 $mailing->getTestRecipients($testParams);
432 // We are still getting all the recipients from the parent job
433 // so we don't mess with the include/exclude logic.
434 $recipients = CRM_Mailing_BAO_Recipients
::mailingQuery($this->mailing_id
, $this->job_offset
, $this->job_limit
);
436 // FIXME: this is not very smart, we should move this to one DB call
437 // INSERT INTO ... SELECT FROM ..
438 // the thing we need to figure out is how to generate the hash automatically
442 while ($recipients->fetch()) {
443 if ($recipients->phone_id
) {
444 $recipients->email_id
= "null";
447 $recipients->phone_id
= "null";
452 $recipients->email_id
,
453 $recipients->contact_id
,
454 $recipients->phone_id
,
457 if ($count % CRM_Core_DAO
::BULK_MAIL_INSERT_COUNT
== 0) {
458 CRM_Mailing_Event_BAO_Queue
::bulkCreate($params, $now);
464 if (!empty($params)) {
465 CRM_Mailing_Event_BAO_Queue
::bulkCreate($params, $now);
473 * @param object $mailer
474 * A Mail object to send the messages.
476 * @param array $testParams
478 public function deliver(&$mailer, $testParams = NULL) {
479 $mailing = new CRM_Mailing_BAO_Mailing();
480 $mailing->id
= $this->mailing_id
;
481 $mailing->find(TRUE);
484 $eq = new CRM_Mailing_Event_BAO_Queue();
485 $eqTable = CRM_Mailing_Event_BAO_Queue
::getTableName();
486 $emailTable = CRM_Core_BAO_Email
::getTableName();
487 $phoneTable = CRM_Core_DAO_Phone
::getTableName();
488 $contactTable = CRM_Contact_BAO_Contact
::getTableName();
489 $edTable = CRM_Mailing_Event_BAO_Delivered
::getTableName();
490 $ebTable = CRM_Mailing_Event_BAO_Bounce
::getTableName();
492 $query = " SELECT $eqTable.id,
493 $emailTable.email as email,
498 INNER JOIN $emailTable
499 ON $eqTable.email_id = $emailTable.id
500 INNER JOIN $contactTable
501 ON $contactTable.id = $emailTable.contact_id
503 ON $eqTable.id = $edTable.event_queue_id
505 ON $eqTable.id = $ebTable.event_queue_id
506 WHERE $eqTable.job_id = " . $this->id
. "
507 AND $edTable.id IS null
508 AND $ebTable.id IS null
509 AND $contactTable.is_opt_out = 0";
511 if ($mailing->sms_provider_id
) {
514 $phoneTable.phone as phone,
519 INNER JOIN $phoneTable
520 ON $eqTable.phone_id = $phoneTable.id
521 INNER JOIN $contactTable
522 ON $contactTable.id = $phoneTable.contact_id
524 ON $eqTable.id = $edTable.event_queue_id
526 ON $eqTable.id = $ebTable.event_queue_id
527 WHERE $eqTable.job_id = " . $this->id
. "
528 AND $edTable.id IS null
529 AND $ebTable.id IS null
530 AND ( $contactTable.is_opt_out = 0
531 OR $contactTable.do_not_sms = 0 )";
537 if ($config == NULL) {
538 $config = CRM_Core_Config
::singleton();
541 if (property_exists($mailing, 'language') && $mailing->language
&& $mailing->language
!= 'en_US') {
542 $swapLang = CRM_Utils_AutoClean
::swap('global://dbLocale?getter', 'call://i18n/setLocale', $mailing->language
);
545 $job_date = CRM_Utils_Date
::isoToMysql($this->scheduled_date
);
548 if (!empty($testParams)) {
549 $mailing->subject
= ts('[CiviMail Draft]') . ' ' . $mailing->subject
;
552 CRM_Mailing_BAO_Mailing
::tokenReplace($mailing);
554 // get and format attachments
555 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_mailing', $mailing->id
);
557 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
558 CRM_Core_Smarty
::registerStringResource();
562 // This handles the edge case scenario where all the mails
563 // have been delivered in prior jobs.
566 // make sure that there's no more than $mailerBatchLimit mails processed in a run
567 $mailerBatchLimit = Civi
::settings()->get('mailerBatchLimit');
568 while ($eq->fetch()) {
569 // if ( ( $mailsProcessed % 100 ) == 0 ) {
570 // CRM_Utils_System::xMemory( "$mailsProcessed: " );
573 if ($mailerBatchLimit > 0 && self
::$mailsProcessed >= $mailerBatchLimit) {
574 if (!empty($fields)) {
575 $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
580 self
::$mailsProcessed++
;
585 'contact_id' => $eq->contact_id
,
586 'email' => $eq->email
,
587 'phone' => $eq->phone
,
589 if (count($fields) == self
::MAX_CONTACTS_TO_PROCESS
) {
590 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
601 if (!empty($fields)) {
602 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
608 * @param array $fields
609 * List of intended recipients.
610 * Each recipient is an array with keys 'hash', 'contact_id', 'email', etc.
614 * @param $attachments
619 public function deliverGroup(&$fields, &$mailing, &$mailer, &$job_date, &$attachments) {
620 static $smtpConnectionErrors = 0;
622 if (!is_object($mailer) ||
empty($fields)) {
623 CRM_Core_Error
::fatal();
626 // get the return properties
627 $returnProperties = $mailing->getReturnProperties();
628 $params = $targetParams = $deliveredParams = array();
631 // CRM-15702: Sending bulk sms to contacts without e-mail address fails.
632 // Solution is to skip checking for on hold
633 $skipOnHold = TRUE; //do include a statement to check wether e-mail address is on hold
634 if ($mailing->sms_provider_id
) {
635 $skipOnHold = FALSE; //do not include a statement to check wether e-mail address is on hold
638 foreach ($fields as $key => $field) {
639 $params[] = $field['contact_id'];
642 $details = CRM_Utils_Token
::getTokenDetails(
645 $skipOnHold, TRUE, NULL,
646 $mailing->getFlattenedTokens(),
651 $config = CRM_Core_Config
::singleton();
652 foreach ($fields as $key => $field) {
653 $contactID = $field['contact_id'];
654 if (!array_key_exists($contactID, $details[0])) {
655 $details[0][$contactID] = array();
658 // Compose the mailing.
659 $recipient = $replyToEmail = NULL;
660 $replyValue = strcmp($mailing->replyto_email
, $mailing->from_email
);
662 $replyToEmail = $mailing->replyto_email
;
665 $message = $mailing->compose(
666 $this->id
, $field['id'], $field['hash'],
667 $field['contact_id'], $field['email'],
668 $recipient, FALSE, $details[0][$contactID], $attachments,
669 FALSE, NULL, $replyToEmail
671 if (empty($message)) {
672 // lets keep the message in the queue
673 // most likely a permissions related issue with smarty templates
674 // or a bad contact id? CRM-9833
680 $body = &$message->get();
681 $headers = &$message->headers();
683 if ($mailing->sms_provider_id
) {
684 $provider = CRM_SMS_Provider
::singleton(array('mailing_id' => $mailing->id
));
685 $body = $provider->getMessage($message, $field['contact_id'], $details[0][$contactID]);
686 $headers = $provider->getRecipientDetails($field, $details[0][$contactID]);
689 // make $recipient actually be the *encoded* header, so as not to baffle Mail_RFC822, CRM-5743
690 $recipient = $headers['To'];
693 // disable error reporting on real mailings (but leave error reporting for tests), CRM-5744
695 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
698 $result = $mailer->send($recipient, $headers, $body, $this->id
);
704 if (is_a($result, 'PEAR_Error') && !$mailing->sms_provider_id
) {
706 $message = $result->getMessage();
708 strpos($message, 'Failed to write to socket') !== FALSE ||
709 strpos($message, 'Failed to set sender') !== FALSE
711 // lets log this message and code
712 $code = $result->getCode();
713 CRM_Core_Error
::debug_log_message("SMTP Socket Error or failed to set sender error. Message: $message, Code: $code");
715 // these are socket write errors which most likely means smtp connection errors
717 $smtpConnectionErrors++
;
718 if ($smtpConnectionErrors <= 5) {
722 // seems like we have too many of them in a row, we should
723 // write stuff to disk and abort the cron job
731 CRM_Core_Error
::debug_log_message("Too many SMTP Socket Errors. Exiting");
732 CRM_Utils_System
::civiExit();
735 // Register the bounce event.
738 'event_queue_id' => $field['id'],
739 'job_id' => $this->id
,
740 'hash' => $field['hash'],
742 $params = array_merge($params,
743 CRM_Mailing_BAO_BouncePattern
::match($result->getMessage())
745 CRM_Mailing_Event_BAO_Bounce
::create($params);
747 elseif (is_a($result, 'PEAR_Error') && $mailing->sms_provider_id
) {
748 // Handle SMS errors: CRM-15426
749 $job_id = intval($this->id
);
750 $mailing_id = intval($mailing->id
);
751 CRM_Core_Error
::debug_log_message("Failed to send SMS message. Vars: mailing_id: ${mailing_id}, job_id: ${job_id}. Error message follows.");
752 CRM_Core_Error
::debug_log_message($result->getMessage());
755 // Register the delivery event.
756 $deliveredParams[] = $field['id'];
757 $targetParams[] = $field['contact_id'];
760 if ($count % CRM_Core_DAO
::BULK_MAIL_INSERT_COUNT
== 0) {
769 // hack to stop mailing job at run time, CRM-4246.
770 // to avoid making too many DB calls for this rare case
771 // lets do it when we snapshot
772 $status = CRM_Core_DAO
::getFieldValue(
773 'CRM_Mailing_DAO_MailingJob',
780 if ($status != 'Running') {
788 // seems like a successful delivery or bounce, lets decrement error count
789 // only if we have smtp connection errors
790 if ($smtpConnectionErrors > 0) {
791 $smtpConnectionErrors--;
794 // If we have enabled the Throttle option, this is the time to enforce it.
795 $mailThrottleTime = Civi
::settings()->get('mailThrottleTime');
796 if (!empty($mailThrottleTime)) {
797 usleep((int ) $mailThrottleTime);
801 $result = $this->writeToDB(
814 * @param int $mailingId
815 * The id of the mailing to be canceled.
817 public static function cancel($mailingId) {
820 FROM civicrm_mailing_job
821 WHERE mailing_id = %1
823 AND ( ( job_type IS NULL ) OR
824 job_type <> 'child' )
826 $params = array(1 => array($mailingId, 'Integer'));
827 $job = CRM_Core_DAO
::executeQuery($sql, $params);
829 in_array($job->status
, array('Scheduled', 'Running', 'Paused'))
832 $newJob = new CRM_Mailing_BAO_MailingJob();
833 $newJob->id
= $job->id
;
834 $newJob->end_date
= date('YmdHis');
835 $newJob->status
= 'Canceled';
838 // also cancel all child jobs
840 UPDATE civicrm_mailing_job
841 SET status = 'Canceled',
845 AND job_type = 'child'
846 AND status IN ( 'Scheduled', 'Running', 'Paused' )
849 1 => array($job->id
, 'Integer'),
850 2 => array(date('YmdHis'), 'Timestamp'),
852 CRM_Core_DAO
::executeQuery($sql, $params);
854 CRM_Core_Session
::setStatus(ts('The mailing has been canceled.'), ts('Canceled'), 'success');
859 * Return a translated status enum string.
861 * @param string $status
865 * The translated version
867 public static function status($status) {
868 static $translation = NULL;
870 if (empty($translation)) {
871 $translation = array(
872 'Scheduled' => ts('Scheduled'),
873 'Running' => ts('Running'),
874 'Complete' => ts('Complete'),
875 'Paused' => ts('Paused'),
876 'Canceled' => ts('Canceled'),
879 return CRM_Utils_Array
::value($status, $translation, ts('Not scheduled'));
883 * Return a workflow clause for use in SQL queries,
884 * to only process jobs that are approved.
887 * For use in a WHERE clause
889 public static function workflowClause() {
890 // add an additional check and only process
891 // jobs that are approved
892 if (CRM_Mailing_Info
::workflowEnabled()) {
893 $approveOptionID = CRM_Core_OptionGroup
::getValue('mail_approval_status',
897 if ($approveOptionID) {
898 return " AND m.approval_status_id = $approveOptionID ";
905 * @param array $deliveredParams
906 * @param array $targetParams
911 * @throws CRM_Core_Exception
914 public function writeToDB(
920 static $activityTypeID = NULL;
921 static $writeActivity = NULL;
923 if (!empty($deliveredParams)) {
924 CRM_Mailing_Event_BAO_Delivered
::bulkCreate($deliveredParams);
925 $deliveredParams = array();
928 if ($writeActivity === NULL) {
929 $writeActivity = CRM_Core_BAO_Setting
::getItem(
930 CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
931 'write_activity_record',
937 if (!$writeActivity) {
942 if (!empty($targetParams) && !empty($mailing->scheduled_id
)) {
943 if (!$activityTypeID) {
944 if ($mailing->sms_provider_id
) {
945 $mailing->subject
= $mailing->name
;
946 $activityTypeID = CRM_Core_OptionGroup
::getValue(
953 $activityTypeID = CRM_Core_OptionGroup
::getValue(
959 if (!$activityTypeID) {
960 CRM_Core_Error
::fatal();
965 'source_contact_id' => $mailing->scheduled_id
,
967 'target_contact_id' => array_unique($targetParams),
968 'activity_type_id' => $activityTypeID,
969 'source_record_id' => $this->mailing_id
,
970 'activity_date_time' => $job_date,
971 'subject' => $mailing->subject
,
973 'deleteActivityTarget' => FALSE,
974 'campaign_id' => $mailing->campaign_id
,
977 //check whether activity is already created for this mailing.
978 //if yes then create only target contact record.
981 FROM civicrm_activity
982 WHERE civicrm_activity.activity_type_id = %1
983 AND civicrm_activity.source_record_id = %2
986 $queryParams = array(
987 1 => array($activityTypeID, 'Integer'),
988 2 => array($this->mailing_id
, 'Integer'),
990 $activityID = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
993 $activity['id'] = $activityID;
996 if (CRM_Core_BAO_Email
::isMultipleBulkMail()) {
997 static $targetRecordID = NULL;
998 if (!$targetRecordID) {
999 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1000 $targetRecordID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1003 // make sure we don't attempt to duplicate the target activity
1004 foreach ($activity['target_contact_id'] as $key => $targetID) {
1007 FROM civicrm_activity_contact
1008 WHERE activity_id = $activityID
1009 AND contact_id = $targetID
1010 AND record_type_id = $targetRecordID
1012 if (CRM_Core_DAO
::singleValueQuery($sql)) {
1013 unset($activity['target_contact_id'][$key]);
1019 if (is_a(CRM_Activity_BAO_Activity
::create($activity), 'CRM_Core_Error')) {
1023 $targetParams = array();