3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
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();
92 $mailerBatchLimit = Civi
::settings()->get('mailerBatchLimit');
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.scheduled_date ASC,
134 while ($job->fetch()) {
135 // still use job level lock for each child job
136 $lock = Civi
::lockManager()->acquire("data.mailing.job.{$job->id}");
137 if (!$lock->isAcquired()) {
141 // for test jobs we do not change anything, since its on a short-circuit path
142 if (empty($testParams)) {
143 // we've got the lock, but while we were waiting and processing
144 // other emails, this job might have changed under us
145 // lets get the job status again and check
146 $job->status
= CRM_Core_DAO
::getFieldValue(
147 'CRM_Mailing_DAO_MailingJob',
155 $job->status
!= 'Running' &&
156 $job->status
!= 'Scheduled'
158 // this includes Cancelled and other statuses, CRM-4246
164 /* Queue up recipients for the child job being launched */
166 if ($job->status
!= 'Running') {
167 $transaction = new CRM_Core_Transaction();
169 // have to queue it up based on the offset and limits
170 // get the parent ID, and limit and offset
171 $job->queue($testParams);
173 // Mark up the starting time
174 $saveJob = new CRM_Mailing_DAO_MailingJob();
175 $saveJob->id
= $job->id
;
176 $saveJob->start_date
= date('YmdHis');
177 $saveJob->status
= 'Running';
180 $transaction->commit();
184 if ($mode === NULL) {
185 $mailer = \Civi
::service('pear_mail');
187 elseif ($mode == 'sms') {
188 $mailer = CRM_SMS_Provider
::singleton(array('mailing_id' => $job->mailing_id
));
191 // Compose and deliver each child job
192 $isComplete = $job->deliver($mailer, $testParams);
194 CRM_Utils_Hook
::post('create', 'CRM_Mailing_DAO_Spool', $job->id
, $isComplete);
196 // Mark the child complete
200 $transaction = new CRM_Core_Transaction();
202 $saveJob = new CRM_Mailing_DAO_MailingJob();
203 $saveJob->id
= $job->id
;
204 $saveJob->end_date
= date('YmdHis');
205 $saveJob->status
= 'Complete';
208 $transaction->commit();
210 // don't mark the mailing as complete
213 // Release the child joblock
220 // CRM-17629: Stop processing jobs if mailer batch limit reached
221 if ($mailerBatchLimit > 0 && self
::$mailsProcessed >= $mailerBatchLimit) {
229 * Post process to determine if the parent job
230 * as well as the mailing is complete after the run.
233 public static function runJobs_post($mode = NULL) {
235 $job = new CRM_Mailing_BAO_MailingJob();
237 $mailing = new CRM_Mailing_BAO_Mailing();
239 $config = CRM_Core_Config
::singleton();
240 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
241 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
243 $currentTime = date('YmdHis');
244 $mailingACL = CRM_Mailing_BAO_Mailing
::mailingACL('m');
245 $domainID = CRM_Core_Config
::domainID();
251 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
253 AND j.scheduled_date <= $currentTime
254 AND j.status = 'Running'
255 AND j.end_date IS null
256 AND (j.job_type != 'child' OR j.job_type is NULL)
257 ORDER BY j.scheduled_date,
262 // For each parent job that is running, let's look at their child jobs
263 while ($job->fetch()) {
265 $child_job = new CRM_Mailing_BAO_MailingJob();
269 FROM civicrm_mailing_job j, civicrm_mailing m
270 WHERE m.id = j.mailing_id
271 AND j.job_type = 'child'
273 AND j.status <> 'Complete'";
274 $params = array(1 => array($job->id
, 'Integer'));
276 $anyChildLeft = CRM_Core_DAO
::singleValueQuery($child_job_sql, $params);
278 // all of the child jobs are complete, update
279 // the parent job as well as the mailing status
280 if (!$anyChildLeft) {
282 $transaction = new CRM_Core_Transaction();
284 $saveJob = new CRM_Mailing_DAO_MailingJob();
285 $saveJob->id
= $job->id
;
286 $saveJob->end_date
= date('YmdHis');
287 $saveJob->status
= 'Complete';
291 $mailing->id
= $job->mailing_id
;
292 $mailing->is_completed
= TRUE;
294 $transaction->commit();
297 CRM_Utils_Hook
::postMailing($job->mailing_id
);
304 * before we run jobs, we need to split the jobs
308 public static function runJobs_pre($offset = 200, $mode = NULL) {
309 $job = new CRM_Mailing_BAO_MailingJob();
311 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
312 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
314 $currentTime = date('YmdHis');
315 $mailingACL = CRM_Mailing_BAO_Mailing
::mailingACL('m');
317 $workflowClause = CRM_Mailing_BAO_MailingJob
::workflowClause();
319 $domainID = CRM_Core_Config
::domainID();
321 $modeClause = 'AND m.sms_provider_id IS NULL';
322 if ($mode == 'sms') {
323 $modeClause = 'AND m.sms_provider_id IS NOT NULL';
326 // Select all the mailing jobs that are created from
327 // when the mailing is submitted or scheduled.
332 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
336 AND ( ( j.start_date IS null
337 AND j.scheduled_date <= $currentTime
338 AND j.status = 'Scheduled'
339 AND j.end_date IS null ) )
340 AND ((j.job_type is NULL) OR (j.job_type <> 'child'))
341 ORDER BY j.scheduled_date,
346 // For each of the "Parent Jobs" we find, we split them into
347 // X Number of child jobs
348 while ($job->fetch()) {
349 // still use job level lock for each child job
350 $lock = Civi
::lockManager()->acquire("data.mailing.job.{$job->id}");
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
389 * Split the parent job into n number of child job based on an offset.
390 * 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();
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)
406 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_Mailing_Config
::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
484 * A Mail object to send the messages.
486 * @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 list($aclJoin, $aclWhere) = CRM_ACL_BAO_ACL
::buildAcl($mailing->created_id
);
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 contact_a
513 ON contact_a.id = $emailTable.contact_id
515 ON $eqTable.id = $edTable.event_queue_id
517 ON $eqTable.id = $ebTable.event_queue_id
519 WHERE $eqTable.job_id = " . $this->id
. "
520 AND $edTable.id IS null
521 AND $ebTable.id IS null
522 AND contact_a.is_opt_out = 0
525 if ($mailing->sms_provider_id
) {
528 $phoneTable.phone as phone,
533 INNER JOIN $phoneTable
534 ON $eqTable.phone_id = $phoneTable.id
535 INNER JOIN $contactTable contact_a
536 ON contact_a.id = $phoneTable.contact_id
538 ON $eqTable.id = $edTable.event_queue_id
540 ON $eqTable.id = $ebTable.event_queue_id
542 WHERE $eqTable.job_id = " . $this->id
. "
543 AND $edTable.id IS null
544 AND $ebTable.id IS null
545 AND ( contact_a.is_opt_out = 0
546 OR contact_a.do_not_sms = 0 )
553 if ($config == NULL) {
554 $config = CRM_Core_Config
::singleton();
557 if (property_exists($mailing, 'language') && $mailing->language
&& $mailing->language
!= 'en_US') {
558 $swapLang = CRM_Utils_AutoClean
::swap('global://dbLocale?getter', 'call://i18n/setLocale', $mailing->language
);
561 $job_date = CRM_Utils_Date
::isoToMysql($this->scheduled_date
);
564 if (!empty($testParams)) {
565 $mailing->subject
= ts('[CiviMail Draft]') . ' ' . $mailing->subject
;
568 CRM_Mailing_BAO_Mailing
::tokenReplace($mailing);
570 // get and format attachments
571 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_mailing', $mailing->id
);
573 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
574 CRM_Core_Smarty
::registerStringResource();
578 // This handles the edge case scenario where all the mails
579 // have been delivered in prior jobs.
582 // make sure that there's no more than $mailerBatchLimit mails processed in a run
583 $mailerBatchLimit = Civi
::settings()->get('mailerBatchLimit');
584 while ($eq->fetch()) {
585 // if ( ( $mailsProcessed % 100 ) == 0 ) {
586 // CRM_Utils_System::xMemory( "$mailsProcessed: " );
589 if ($mailerBatchLimit > 0 && self
::$mailsProcessed >= $mailerBatchLimit) {
590 if (!empty($fields)) {
591 $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
596 self
::$mailsProcessed++
;
601 'contact_id' => $eq->contact_id
,
602 'email' => $eq->email
,
603 'phone' => $eq->phone
,
605 if (count($fields) == self
::MAX_CONTACTS_TO_PROCESS
) {
606 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
617 if (!empty($fields)) {
618 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
624 * @param array $fields
625 * List of intended recipients.
626 * Each recipient is an array with keys 'hash', 'contact_id', 'email', etc.
630 * @param $attachments
635 public function deliverGroup(&$fields, &$mailing, &$mailer, &$job_date, &$attachments) {
636 static $smtpConnectionErrors = 0;
638 if (!is_object($mailer) ||
empty($fields)) {
639 CRM_Core_Error
::fatal();
642 // get the return properties
643 $returnProperties = $mailing->getReturnProperties();
644 $params = $targetParams = $deliveredParams = array();
647 // CRM-15702: Sending bulk sms to contacts without e-mail address fails.
648 // Solution is to skip checking for on hold
649 $skipOnHold = TRUE; //do include a statement to check wether e-mail address is on hold
650 if ($mailing->sms_provider_id
) {
651 $skipOnHold = FALSE; //do not include a statement to check wether e-mail address is on hold
654 foreach ($fields as $key => $field) {
655 $params[] = $field['contact_id'];
658 $details = CRM_Utils_Token
::getTokenDetails(
661 $skipOnHold, TRUE, NULL,
662 $mailing->getFlattenedTokens(),
667 $config = CRM_Core_Config
::singleton();
668 foreach ($fields as $key => $field) {
669 $contactID = $field['contact_id'];
670 if (!array_key_exists($contactID, $details[0])) {
671 $details[0][$contactID] = array();
674 // Compose the mailing.
675 $recipient = $replyToEmail = NULL;
676 $replyValue = strcmp($mailing->replyto_email
, $mailing->from_email
);
678 $replyToEmail = $mailing->replyto_email
;
681 $message = $mailing->compose(
682 $this->id
, $field['id'], $field['hash'],
683 $field['contact_id'], $field['email'],
684 $recipient, FALSE, $details[0][$contactID], $attachments,
685 FALSE, NULL, $replyToEmail
687 if (empty($message)) {
688 // lets keep the message in the queue
689 // most likely a permissions related issue with smarty templates
690 // or a bad contact id? CRM-9833
696 $body = &$message->get();
697 $headers = &$message->headers();
699 if ($mailing->sms_provider_id
) {
700 $provider = CRM_SMS_Provider
::singleton(array('mailing_id' => $mailing->id
));
701 $body = $provider->getMessage($message, $field['contact_id'], $details[0][$contactID]);
702 $headers = $provider->getRecipientDetails($field, $details[0][$contactID]);
705 // make $recipient actually be the *encoded* header, so as not to baffle Mail_RFC822, CRM-5743
706 $recipient = $headers['To'];
709 // disable error reporting on real mailings (but leave error reporting for tests), CRM-5744
711 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
714 $result = $mailer->send($recipient, $headers, $body, $this->id
);
720 if (is_a($result, 'PEAR_Error') && !$mailing->sms_provider_id
) {
722 $message = $result->getMessage();
724 strpos($message, 'Failed to write to socket') !== FALSE ||
725 strpos($message, 'Failed to set sender') !== FALSE
727 // lets log this message and code
728 $code = $result->getCode();
729 CRM_Core_Error
::debug_log_message("SMTP Socket Error or failed to set sender error. Message: $message, Code: $code");
731 // these are socket write errors which most likely means smtp connection errors
733 $smtpConnectionErrors++
;
734 if ($smtpConnectionErrors <= 5) {
738 // seems like we have too many of them in a row, we should
739 // write stuff to disk and abort the cron job
747 CRM_Core_Error
::debug_log_message("Too many SMTP Socket Errors. Exiting");
748 CRM_Utils_System
::civiExit();
751 // Register the bounce event.
754 'event_queue_id' => $field['id'],
755 'job_id' => $this->id
,
756 'hash' => $field['hash'],
758 $params = array_merge($params,
759 CRM_Mailing_BAO_BouncePattern
::match($result->getMessage())
761 CRM_Mailing_Event_BAO_Bounce
::create($params);
763 elseif (is_a($result, 'PEAR_Error') && $mailing->sms_provider_id
) {
764 // Handle SMS errors: CRM-15426
765 $job_id = intval($this->id
);
766 $mailing_id = intval($mailing->id
);
767 CRM_Core_Error
::debug_log_message("Failed to send SMS message. Vars: mailing_id: ${mailing_id}, job_id: ${job_id}. Error message follows.");
768 CRM_Core_Error
::debug_log_message($result->getMessage());
771 // Register the delivery event.
772 $deliveredParams[] = $field['id'];
773 $targetParams[] = $field['contact_id'];
776 if ($count % CRM_Mailing_Config
::BULK_MAIL_INSERT_COUNT
== 0) {
785 // hack to stop mailing job at run time, CRM-4246.
786 // to avoid making too many DB calls for this rare case
787 // lets do it when we snapshot
788 $status = CRM_Core_DAO
::getFieldValue(
789 'CRM_Mailing_DAO_MailingJob',
796 if ($status != 'Running') {
804 // seems like a successful delivery or bounce, lets decrement error count
805 // only if we have smtp connection errors
806 if ($smtpConnectionErrors > 0) {
807 $smtpConnectionErrors--;
810 // If we have enabled the Throttle option, this is the time to enforce it.
811 $mailThrottleTime = Civi
::settings()->get('mailThrottleTime');
812 if (!empty($mailThrottleTime)) {
813 usleep((int ) $mailThrottleTime);
817 $result = $this->writeToDB(
830 * @param int $mailingId
831 * The id of the mailing to be canceled.
833 public static function cancel($mailingId) {
836 FROM civicrm_mailing_job
837 WHERE mailing_id = %1
839 AND ( ( job_type IS NULL ) OR
840 job_type <> 'child' )
842 $params = array(1 => array($mailingId, 'Integer'));
843 $job = CRM_Core_DAO
::executeQuery($sql, $params);
845 in_array($job->status
, array('Scheduled', 'Running', 'Paused'))
848 $newJob = new CRM_Mailing_BAO_MailingJob();
849 $newJob->id
= $job->id
;
850 $newJob->end_date
= date('YmdHis');
851 $newJob->status
= 'Canceled';
854 // also cancel all child jobs
856 UPDATE civicrm_mailing_job
857 SET status = 'Canceled',
861 AND job_type = 'child'
862 AND status IN ( 'Scheduled', 'Running', 'Paused' )
865 1 => array($job->id
, 'Integer'),
866 2 => array(date('YmdHis'), 'Timestamp'),
868 CRM_Core_DAO
::executeQuery($sql, $params);
870 CRM_Core_Session
::setStatus(ts('The mailing has been canceled.'), ts('Canceled'), 'success');
875 * Return a translated status enum string.
877 * @param string $status
881 * The translated version
883 public static function status($status) {
884 static $translation = NULL;
886 if (empty($translation)) {
887 $translation = array(
888 'Scheduled' => ts('Scheduled'),
889 'Running' => ts('Running'),
890 'Complete' => ts('Complete'),
891 'Paused' => ts('Paused'),
892 'Canceled' => ts('Canceled'),
895 return CRM_Utils_Array
::value($status, $translation, ts('Not scheduled'));
899 * Return a workflow clause for use in SQL queries,
900 * to only process jobs that are approved.
903 * For use in a WHERE clause
905 public static function workflowClause() {
906 // add an additional check and only process
907 // jobs that are approved
908 if (CRM_Mailing_Info
::workflowEnabled()) {
909 $approveOptionID = CRM_Core_OptionGroup
::getValue('mail_approval_status',
913 if ($approveOptionID) {
914 return " AND m.approval_status_id = $approveOptionID ";
921 * @param array $deliveredParams
922 * @param array $targetParams
927 * @throws CRM_Core_Exception
930 public function writeToDB(
936 static $activityTypeID = NULL;
937 static $writeActivity = NULL;
939 if (!empty($deliveredParams)) {
940 CRM_Mailing_Event_BAO_Delivered
::bulkCreate($deliveredParams);
941 $deliveredParams = array();
944 if ($writeActivity === NULL) {
945 $writeActivity = Civi
::settings()->get('write_activity_record');
948 if (!$writeActivity) {
953 if (!empty($targetParams) && !empty($mailing->scheduled_id
)) {
954 if (!$activityTypeID) {
955 if ($mailing->sms_provider_id
) {
956 $mailing->subject
= $mailing->name
;
957 $activityTypeID = CRM_Core_OptionGroup
::getValue(
964 $activityTypeID = CRM_Core_OptionGroup
::getValue(
970 if (!$activityTypeID) {
971 CRM_Core_Error
::fatal();
976 'source_contact_id' => $mailing->scheduled_id
,
978 'target_contact_id' => array_unique($targetParams),
979 'activity_type_id' => $activityTypeID,
980 'source_record_id' => $this->mailing_id
,
981 'activity_date_time' => $job_date,
982 'subject' => $mailing->subject
,
984 'deleteActivityTarget' => FALSE,
985 'campaign_id' => $mailing->campaign_id
,
988 //check whether activity is already created for this mailing.
989 //if yes then create only target contact record.
992 FROM civicrm_activity
993 WHERE civicrm_activity.activity_type_id = %1
994 AND civicrm_activity.source_record_id = %2
997 $queryParams = array(
998 1 => array($activityTypeID, 'Integer'),
999 2 => array($this->mailing_id
, 'Integer'),
1001 $activityID = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
1004 $activity['id'] = $activityID;
1007 if (CRM_Core_BAO_Email
::isMultipleBulkMail()) {
1008 static $targetRecordID = NULL;
1009 if (!$targetRecordID) {
1010 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1011 $targetRecordID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1014 // make sure we don't attempt to duplicate the target activity
1015 foreach ($activity['target_contact_id'] as $key => $targetID) {
1018 FROM civicrm_activity_contact
1019 WHERE activity_id = $activityID
1020 AND contact_id = $targetID
1021 AND record_type_id = $targetRecordID
1023 if (CRM_Core_DAO
::singleValueQuery($sql)) {
1024 unset($activity['target_contact_id'][$key]);
1030 if (is_a(CRM_Activity_BAO_Activity
::create($activity), 'CRM_Core_Error')) {
1034 $targetParams = array();