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
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
50 static $mailsProcessed = 0;
55 public function __construct() {
56 parent
::__construct();
60 * @param array $params
62 * @return CRM_Mailing_BAO_MailingJob
64 static public function create($params) {
65 $job = new CRM_Mailing_BAO_MailingJob();
66 $job->mailing_id
= $params['mailing_id'];
67 $job->status
= $params['status'];
68 $job->scheduled_date
= $params['scheduled_date'];
69 $job->is_test
= $params['is_test'];
71 $mailing = new CRM_Mailing_BAO_Mailing();
72 $mailing->id
= $params['mailing_id'];
73 if ($mailing->id
&& $mailing->find(TRUE)) {
74 $mailing->getRecipients($job->id
, $params['mailing_id'], TRUE, $mailing->dedupe_email
);
78 throw new CRM_Core_Exception("Failed to create job: Unknown mailing ID");
83 * Initiate all pending/ready jobs
85 * @param array $testParams
90 public static function runJobs($testParams = NULL, $mode = NULL) {
91 $job = new CRM_Mailing_BAO_MailingJob();
93 $config = CRM_Core_Config
::singleton();
94 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
95 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
97 if (!empty($testParams)) {
101 WHERE id = {$testParams['job_id']}";
105 $currentTime = date('YmdHis');
106 $mailingACL = CRM_Mailing_BAO_Mailing
::mailingACL('m');
107 $domainID = CRM_Core_Config
::domainID();
109 $modeClause = 'AND m.sms_provider_id IS NULL';
110 if ($mode == 'sms') {
111 $modeClause = 'AND m.sms_provider_id IS NOT NULL';
114 // Select the first child job that is scheduled
120 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
123 AND ( ( j.start_date IS null
124 AND j.scheduled_date <= $currentTime
125 AND j.status = 'Scheduled' )
126 OR ( j.status = 'Running'
127 AND j.end_date IS null ) )
128 AND (j.job_type = 'child')
130 ORDER BY j.mailing_id,
137 while ($job->fetch()) {
138 // still use job level lock for each child job
139 $lock = Civi
::service('lockManager')->acquire("data.mailing.job.{$job->id}");
140 if (!$lock->isAcquired()) {
144 // for test jobs we do not change anything, since its on a short-circuit path
145 if (empty($testParams)) {
146 // we've got the lock, but while we were waiting and processing
147 // other emails, this job might have changed under us
148 // lets get the job status again and check
149 $job->status
= CRM_Core_DAO
::getFieldValue(
150 'CRM_Mailing_DAO_MailingJob',
158 $job->status
!= 'Running' &&
159 $job->status
!= 'Scheduled'
161 // this includes Cancelled and other statuses, CRM-4246
167 /* Queue up recipients for the child job being launched */
169 if ($job->status
!= 'Running') {
170 $transaction = new CRM_Core_Transaction();
172 // have to queue it up based on the offset and limits
173 // get the parent ID, and limit and offset
174 $job->queue($testParams);
176 // Mark up the starting time
177 $saveJob = new CRM_Mailing_DAO_MailingJob();
178 $saveJob->id
= $job->id
;
179 $saveJob->start_date
= date('YmdHis');
180 $saveJob->status
= 'Running';
183 $transaction->commit();
187 if ($mode === NULL) {
188 $mailer = \Civi
::service('pear_mail');
190 elseif ($mode == 'sms') {
191 $mailer = CRM_SMS_Provider
::singleton(array('mailing_id' => $job->mailing_id
));
194 // Compose and deliver each child job
195 $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
226 * post process to determine if the parent job.
227 * 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();
298 * 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');
311 $workflowClause = CRM_Mailing_BAO_MailingJob
::workflowClause();
313 $domainID = CRM_Core_Config
::domainID();
315 $modeClause = 'AND m.sms_provider_id IS NULL';
316 if ($mode == 'sms') {
317 $modeClause = 'AND m.sms_provider_id IS NOT NULL';
320 // Select all the mailing jobs that are created from
321 // when the mailing is submitted or scheduled.
326 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
330 AND ( ( j.start_date IS null
331 AND j.scheduled_date <= $currentTime
332 AND j.status = 'Scheduled'
333 AND j.end_date IS null ) )
334 AND ((j.job_type is NULL) OR (j.job_type <> 'child'))
335 ORDER BY j.scheduled_date,
340 // For each of the "Parent Jobs" we find, we split them into
341 // X Number of child jobs
342 while ($job->fetch()) {
343 // still use job level lock for each child job
344 $lock = Civi
::service('lockManager')->acquire("data.mailing.job.{$job->id}");
345 if (!$lock->isAcquired()) {
349 // Re-fetch the job status in case things
350 // changed between the first query and now
351 // to avoid race conditions
352 $job->status
= CRM_Core_DAO
::getFieldValue(
353 'CRM_Mailing_DAO_MailingJob',
359 if ($job->status
!= 'Scheduled') {
364 $job->split_job($offset);
366 // update the status of the parent job
367 $transaction = new CRM_Core_Transaction();
369 $saveJob = new CRM_Mailing_DAO_MailingJob();
370 $saveJob->id
= $job->id
;
371 $saveJob->start_date
= date('YmdHis');
372 $saveJob->status
= 'Running';
375 $transaction->commit();
377 // Release the job lock
383 * Split the parent job into n number of child job based on an offset.
384 * If null or 0 , we create only one child job
387 public function split_job($offset = 200) {
388 $recipient_count = CRM_Mailing_BAO_Recipients
::mailingSize($this->mailing_id
);
390 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
392 $dao = new CRM_Core_DAO();
395 INSERT INTO civicrm_mailing_job
396 (`mailing_id`, `scheduled_date`, `status`, `job_type`, `parent_id`, `job_offset`, `job_limit`)
397 VALUES (%1, %2, %3, %4, %5, %6, %7)
400 1 => array($this->mailing_id
, 'Integer'),
401 2 => array($this->scheduled_date
, 'String'),
402 3 => array('Scheduled', 'String'),
403 4 => array('child', 'String'),
404 5 => array($this->id
, 'Integer'),
405 6 => array(0, 'Integer'),
406 7 => array($recipient_count, 'Integer'),
409 // create one child job if the mailing size is less than the offset
410 // probably use a CRM_Mailing_DAO_MailingJob( );
411 if (empty($offset) ||
412 $recipient_count <= $offset
414 CRM_Core_DAO
::executeQuery($sql, $params);
417 // Creating 'child jobs'
418 for ($i = 0; $i < $recipient_count; $i = $i +
$offset) {
420 $params[7][0] = $offset;
421 CRM_Core_DAO
::executeQuery($sql, $params);
427 * @param array $testParams
429 public function queue($testParams = NULL) {
430 $mailing = new CRM_Mailing_BAO_Mailing();
431 $mailing->id
= $this->mailing_id
;
432 if (!empty($testParams)) {
433 $mailing->getTestRecipients($testParams);
436 // We are still getting all the recipients from the parent job
437 // so we don't mess with the include/exclude logic.
438 $recipients = CRM_Mailing_BAO_Recipients
::mailingQuery($this->mailing_id
, $this->job_offset
, $this->job_limit
);
440 // FIXME: this is not very smart, we should move this to one DB call
441 // INSERT INTO ... SELECT FROM ..
442 // the thing we need to figure out is how to generate the hash automatically
446 while ($recipients->fetch()) {
447 if ($recipients->phone_id
) {
448 $recipients->email_id
= "null";
451 $recipients->phone_id
= "null";
456 $recipients->email_id
,
457 $recipients->contact_id
,
458 $recipients->phone_id
,
461 if ($count % CRM_Core_DAO
::BULK_MAIL_INSERT_COUNT
== 0) {
462 CRM_Mailing_Event_BAO_Queue
::bulkCreate($params, $now);
468 if (!empty($params)) {
469 CRM_Mailing_Event_BAO_Queue
::bulkCreate($params, $now);
477 * @param object $mailer
478 * A Mail object to send the messages.
480 * @param array $testParams
484 public function deliver(&$mailer, $testParams = NULL) {
485 $mailing = new CRM_Mailing_BAO_Mailing();
486 $mailing->id
= $this->mailing_id
;
487 $mailing->find(TRUE);
490 $eq = new CRM_Mailing_Event_BAO_Queue();
491 $eqTable = CRM_Mailing_Event_BAO_Queue
::getTableName();
492 $emailTable = CRM_Core_BAO_Email
::getTableName();
493 $phoneTable = CRM_Core_DAO_Phone
::getTableName();
494 $contactTable = CRM_Contact_BAO_Contact
::getTableName();
495 $edTable = CRM_Mailing_Event_BAO_Delivered
::getTableName();
496 $ebTable = CRM_Mailing_Event_BAO_Bounce
::getTableName();
498 $query = " SELECT $eqTable.id,
499 $emailTable.email as email,
504 INNER JOIN $emailTable
505 ON $eqTable.email_id = $emailTable.id
506 INNER JOIN $contactTable
507 ON $contactTable.id = $emailTable.contact_id
509 ON $eqTable.id = $edTable.event_queue_id
511 ON $eqTable.id = $ebTable.event_queue_id
512 WHERE $eqTable.job_id = " . $this->id
. "
513 AND $edTable.id IS null
514 AND $ebTable.id IS null
515 AND $contactTable.is_opt_out = 0";
517 if ($mailing->sms_provider_id
) {
520 $phoneTable.phone as phone,
525 INNER JOIN $phoneTable
526 ON $eqTable.phone_id = $phoneTable.id
527 INNER JOIN $contactTable
528 ON $contactTable.id = $phoneTable.contact_id
530 ON $eqTable.id = $edTable.event_queue_id
532 ON $eqTable.id = $ebTable.event_queue_id
533 WHERE $eqTable.job_id = " . $this->id
. "
534 AND $edTable.id IS null
535 AND $ebTable.id IS null
536 AND ( $contactTable.is_opt_out = 0
537 OR $contactTable.do_not_sms = 0 )";
543 if ($config == NULL) {
544 $config = CRM_Core_Config
::singleton();
547 $job_date = CRM_Utils_Date
::isoToMysql($this->scheduled_date
);
550 if (!empty($testParams)) {
551 $mailing->subject
= ts('[CiviMail Draft]') . ' ' . $mailing->subject
;
554 CRM_Mailing_BAO_Mailing
::tokenReplace($mailing);
556 // get and format attachments
557 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_mailing', $mailing->id
);
559 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
560 CRM_Core_Smarty
::registerStringResource();
564 // This handles the edge case scenario where all the mails
565 // have been delivered in prior jobs
568 // make sure that there's no more than $mailerBatchLimit mails processed in a run
569 $mailerBatchLimit = Civi
::settings()->get('mailerBatchLimit');
570 while ($eq->fetch()) {
571 // if ( ( $mailsProcessed % 100 ) == 0 ) {
572 // CRM_Utils_System::xMemory( "$mailsProcessed: " );
575 if ($mailerBatchLimit > 0 && self
::$mailsProcessed >= $mailerBatchLimit) {
576 if (!empty($fields)) {
577 $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
582 self
::$mailsProcessed++
;
587 'contact_id' => $eq->contact_id
,
588 'email' => $eq->email
,
589 'phone' => $eq->phone
,
591 if (count($fields) == self
::MAX_CONTACTS_TO_PROCESS
) {
592 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
603 if (!empty($fields)) {
604 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
610 * @param array $fields
611 * List of intended recipients.
612 * Each recipient is an array with keys 'hash', 'contact_id', 'email', etc.
616 * @param $attachments
621 public function deliverGroup(&$fields, &$mailing, &$mailer, &$job_date, &$attachments) {
622 static $smtpConnectionErrors = 0;
624 if (!is_object($mailer) ||
empty($fields)) {
625 CRM_Core_Error
::fatal();
628 // get the return properties
629 $returnProperties = $mailing->getReturnProperties();
630 $params = $targetParams = $deliveredParams = array();
634 * CRM-15702: Sending bulk sms to contacts without e-mail address fails.
635 * Solution is to skip checking for on hold
637 $skipOnHold = TRUE; //do include a statement to check wether e-mail address is on hold
638 if ($mailing->sms_provider_id
) {
639 $skipOnHold = FALSE; //do not include a statement to check wether e-mail address is on hold
642 foreach ($fields as $key => $field) {
643 $params[] = $field['contact_id'];
646 $details = CRM_Utils_Token
::getTokenDetails(
649 $skipOnHold, TRUE, NULL,
650 $mailing->getFlattenedTokens(),
655 $config = CRM_Core_Config
::singleton();
656 foreach ($fields as $key => $field) {
657 $contactID = $field['contact_id'];
658 if (!array_key_exists($contactID, $details[0])) {
659 $details[0][$contactID] = array();
662 /* Compose the mailing */
663 $recipient = $replyToEmail = NULL;
664 $replyValue = strcmp($mailing->replyto_email
, $mailing->from_email
);
666 $replyToEmail = $mailing->replyto_email
;
669 $message = $mailing->compose(
670 $this->id
, $field['id'], $field['hash'],
671 $field['contact_id'], $field['email'],
672 $recipient, FALSE, $details[0][$contactID], $attachments,
673 FALSE, NULL, $replyToEmail
675 if (empty($message)) {
676 // lets keep the message in the queue
677 // most likely a permissions related issue with smarty templates
678 // or a bad contact id? CRM-9833
682 /* Send the mailing */
684 $body = &$message->get();
685 $headers = &$message->headers();
687 if ($mailing->sms_provider_id
) {
688 $provider = CRM_SMS_Provider
::singleton(array('mailing_id' => $mailing->id
));
689 $body = $provider->getMessage($message, $field['contact_id'], $details[0][$contactID]);
690 $headers = $provider->getRecipientDetails($field, $details[0][$contactID]);
693 // make $recipient actually be the *encoded* header, so as not to baffle Mail_RFC822, CRM-5743
694 $recipient = $headers['To'];
697 // disable error reporting on real mailings (but leave error reporting for tests), CRM-5744
699 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
702 $result = $mailer->send($recipient, $headers, $body, $this->id
);
708 if (is_a($result, 'PEAR_Error') && !$mailing->sms_provider_id
) {
710 $message = $result->getMessage();
712 strpos($message, 'Failed to write to socket') !== FALSE ||
713 strpos($message, 'Failed to set sender') !== FALSE
715 // lets log this message and code
716 $code = $result->getCode();
717 CRM_Core_Error
::debug_log_message("SMTP Socket Error or failed to set sender error. Message: $message, Code: $code");
719 // these are socket write errors which most likely means smtp connection errors
721 $smtpConnectionErrors++
;
722 if ($smtpConnectionErrors <= 5) {
726 // seems like we have too many of them in a row, we should
727 // write stuff to disk and abort the cron job
735 CRM_Core_Error
::debug_log_message("Too many SMTP Socket Errors. Exiting");
736 CRM_Utils_System
::civiExit();
739 /* Register the bounce event */
742 'event_queue_id' => $field['id'],
743 'job_id' => $this->id
,
744 'hash' => $field['hash'],
746 $params = array_merge($params,
747 CRM_Mailing_BAO_BouncePattern
::match($result->getMessage())
749 CRM_Mailing_Event_BAO_Bounce
::create($params);
751 elseif (is_a($result, 'PEAR_Error') && $mailing->sms_provider_id
) {
752 // Handle SMS errors: CRM-15426
753 $job_id = intval($this->id
);
754 $mailing_id = intval($mailing->id
);
755 CRM_Core_Error
::debug_log_message("Failed to send SMS message. Vars: mailing_id: ${mailing_id}, job_id: ${job_id}. Error message follows.");
756 CRM_Core_Error
::debug_log_message($result->getMessage());
759 /* Register the delivery event */
760 $deliveredParams[] = $field['id'];
761 $targetParams[] = $field['contact_id'];
764 if ($count % CRM_Core_DAO
::BULK_MAIL_INSERT_COUNT
== 0) {
773 // hack to stop mailing job at run time, CRM-4246.
774 // to avoid making too many DB calls for this rare case
775 // lets do it when we snapshot
776 $status = CRM_Core_DAO
::getFieldValue(
777 'CRM_Mailing_DAO_MailingJob',
784 if ($status != 'Running') {
792 // seems like a successful delivery or bounce, lets decrement error count
793 // only if we have smtp connection errors
794 if ($smtpConnectionErrors > 0) {
795 $smtpConnectionErrors--;
798 // If we have enabled the Throttle option, this is the time to enforce it.
799 $mailThrottleTime = Civi
::settings()->get('mailThrottleTime');
800 if (!empty($mailThrottleTime)) {
801 usleep((int ) $mailThrottleTime);
805 $result = $this->writeToDB(
818 * @param int $mailingId
819 * The id of the mailing to be canceled.
821 public static function cancel($mailingId) {
824 FROM civicrm_mailing_job
825 WHERE mailing_id = %1
827 AND ( ( job_type IS NULL ) OR
828 job_type <> 'child' )
830 $params = array(1 => array($mailingId, 'Integer'));
831 $job = CRM_Core_DAO
::executeQuery($sql, $params);
833 in_array($job->status
, array('Scheduled', 'Running', 'Paused'))
836 $newJob = new CRM_Mailing_BAO_MailingJob();
837 $newJob->id
= $job->id
;
838 $newJob->end_date
= date('YmdHis');
839 $newJob->status
= 'Canceled';
842 // also cancel all child jobs
844 UPDATE civicrm_mailing_job
845 SET status = 'Canceled',
849 AND job_type = 'child'
850 AND status IN ( 'Scheduled', 'Running', 'Paused' )
853 1 => array($job->id
, 'Integer'),
854 2 => array(date('YmdHis'), 'Timestamp'),
856 CRM_Core_DAO
::executeQuery($sql, $params);
858 CRM_Core_Session
::setStatus(ts('The mailing has been canceled.'), ts('Canceled'), 'success');
863 * Return a translated status enum string.
865 * @param string $status
869 * The translated version
871 public static function status($status) {
872 static $translation = NULL;
874 if (empty($translation)) {
875 $translation = array(
876 'Scheduled' => ts('Scheduled'),
877 'Running' => ts('Running'),
878 'Complete' => ts('Complete'),
879 'Paused' => ts('Paused'),
880 'Canceled' => ts('Canceled'),
883 return CRM_Utils_Array
::value($status, $translation, ts('Not scheduled'));
887 * Return a workflow clause for use in SQL queries,
888 * to only process jobs that are approved.
891 * For use in a WHERE clause
893 public static function workflowClause() {
894 // add an additional check and only process
895 // jobs that are approved
896 if (CRM_Mailing_Info
::workflowEnabled()) {
897 $approveOptionID = CRM_Core_OptionGroup
::getValue('mail_approval_status',
901 if ($approveOptionID) {
902 return " AND m.approval_status_id = $approveOptionID ";
909 * @param array $deliveredParams
910 * @param array $targetParams
915 * @throws CRM_Core_Exception
918 public function writeToDB(
924 static $activityTypeID = NULL;
925 static $writeActivity = NULL;
927 if (!empty($deliveredParams)) {
928 CRM_Mailing_Event_BAO_Delivered
::bulkCreate($deliveredParams);
929 $deliveredParams = array();
932 if ($writeActivity === NULL) {
933 $writeActivity = CRM_Core_BAO_Setting
::getItem(
934 CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
935 'write_activity_record',
941 if (!$writeActivity) {
946 if (!empty($targetParams) && !empty($mailing->scheduled_id
)) {
947 if (!$activityTypeID) {
948 if ($mailing->sms_provider_id
) {
949 $mailing->subject
= $mailing->name
;
950 $activityTypeID = CRM_Core_OptionGroup
::getValue(
957 $activityTypeID = CRM_Core_OptionGroup
::getValue(
963 if (!$activityTypeID) {
964 CRM_Core_Error
::fatal();
969 'source_contact_id' => $mailing->scheduled_id
,
971 'target_contact_id' => array_unique($targetParams),
972 'activity_type_id' => $activityTypeID,
973 'source_record_id' => $this->mailing_id
,
974 'activity_date_time' => $job_date,
975 'subject' => $mailing->subject
,
977 'deleteActivityTarget' => FALSE,
978 'campaign_id' => $mailing->campaign_id
,
981 //check whether activity is already created for this mailing.
982 //if yes then create only target contact record.
985 FROM civicrm_activity
986 WHERE civicrm_activity.activity_type_id = %1
987 AND civicrm_activity.source_record_id = %2
990 $queryParams = array(
991 1 => array($activityTypeID, 'Integer'),
992 2 => array($this->mailing_id
, 'Integer'),
994 $activityID = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
997 $activity['id'] = $activityID;
1000 if (CRM_Core_BAO_Email
::isMultipleBulkMail()) {
1001 static $targetRecordID = NULL;
1002 if (!$targetRecordID) {
1003 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1004 $targetRecordID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1007 // make sure we don't attempt to duplicate the target activity
1008 foreach ($activity['target_contact_id'] as $key => $targetID) {
1011 FROM civicrm_activity_contact
1012 WHERE activity_id = $activityID
1013 AND contact_id = $targetID
1014 AND record_type_id = $targetRecordID
1016 if (CRM_Core_DAO
::singleValueQuery($sql)) {
1017 unset($activity['target_contact_id'][$key]);
1023 if (is_a(CRM_Activity_BAO_Activity
::create($activity), 'CRM_Core_Error')) {
1027 $targetParams = array();