3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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();
60 * @param array $params
62 * @return \CRM_Mailing_BAO_MailingJob
63 * @throws \CRM_Core_Exception
65 static public function create($params) {
66 if (empty($params['id']) && empty($params['mailing_id'])) {
67 throw new CRM_Core_Exception("Failed to create job: Unknown mailing ID");
69 $op = empty($params['id']) ?
'create' : 'edit';
70 CRM_Utils_Hook
::pre($op, 'MailingJob', CRM_Utils_Array
::value('id', $params), $params);
72 $jobDAO = new CRM_Mailing_BAO_MailingJob();
73 $jobDAO->copyValues($params, TRUE);
75 if (!empty($params['mailing_id'])) {
76 CRM_Mailing_BAO_Mailing
::getRecipients($params['mailing_id']);
78 CRM_Utils_Hook
::post($op, 'MailingJob', $jobDAO->id
, $jobDAO);
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 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
94 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
95 $mailerBatchLimit = Civi
::settings()->get('mailerBatchLimit');
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.scheduled_date ASC,
137 while ($job->fetch()) {
138 // still use job level lock for each child job
139 $lock = Civi
::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 // Update to show job has started.
179 'start_date' => date('YmdHis'),
180 '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 if (\CRM_Utils_Constant
::value('CIVICRM_FLEXMAILER_HACK_DELIVER')) {
196 $isComplete = Civi\Core\Resolver
::singleton()->call(CIVICRM_FLEXMAILER_HACK_DELIVER
, array($job, $mailer, $testParams));
199 $isComplete = $job->deliver($mailer, $testParams);
202 CRM_Utils_Hook
::post('create', 'CRM_Mailing_DAO_Spool', $job->id
, $isComplete);
204 // Mark the child complete
208 $transaction = new CRM_Core_Transaction();
209 self
::create(['id' => $job->id
, 'end_date' => date('YmdHis'), 'status' => 'Complete']);
210 $transaction->commit();
212 // don't mark the mailing as complete
215 // Release the child joblock
222 // CRM-17629: Stop processing jobs if mailer batch limit reached
223 if ($mailerBatchLimit > 0 && self
::$mailsProcessed >= $mailerBatchLimit) {
231 * Post process to determine if the parent job
232 * as well as the mailing is complete after the run.
235 public static function runJobs_post($mode = NULL) {
237 $job = new CRM_Mailing_BAO_MailingJob();
239 $mailing = new CRM_Mailing_BAO_Mailing();
241 $config = CRM_Core_Config
::singleton();
242 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
243 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
245 $currentTime = date('YmdHis');
246 $mailingACL = CRM_Mailing_BAO_Mailing
::mailingACL('m');
247 $domainID = CRM_Core_Config
::domainID();
253 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
255 AND j.scheduled_date <= $currentTime
256 AND j.status = 'Running'
257 AND j.end_date IS null
258 AND (j.job_type != 'child' OR j.job_type is NULL)
259 ORDER BY j.scheduled_date,
264 // For each parent job that is running, let's look at their child jobs
265 while ($job->fetch()) {
267 $child_job = new CRM_Mailing_BAO_MailingJob();
271 FROM civicrm_mailing_job j, civicrm_mailing m
272 WHERE m.id = j.mailing_id
273 AND j.job_type = 'child'
275 AND j.status <> 'Complete'";
276 $params = array(1 => array($job->id
, 'Integer'));
278 $anyChildLeft = CRM_Core_DAO
::singleValueQuery($child_job_sql, $params);
280 // all of the child jobs are complete, update
281 // the parent job as well as the mailing status
282 if (!$anyChildLeft) {
284 $transaction = new CRM_Core_Transaction();
286 $saveJob = new CRM_Mailing_DAO_MailingJob();
287 $saveJob->id
= $job->id
;
288 $saveJob->end_date
= date('YmdHis');
289 $saveJob->status
= 'Complete';
293 $mailing->id
= $job->mailing_id
;
294 $mailing->is_completed
= TRUE;
296 $transaction->commit();
299 CRM_Utils_Hook
::postMailing($job->mailing_id
);
306 * before we run jobs, we need to split the jobs
310 public static function runJobs_pre($offset = 200, $mode = NULL) {
311 $job = new CRM_Mailing_BAO_MailingJob();
313 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
314 $mailingTable = CRM_Mailing_DAO_Mailing
::getTableName();
316 $currentTime = date('YmdHis');
317 $mailingACL = CRM_Mailing_BAO_Mailing
::mailingACL('m');
319 $workflowClause = CRM_Mailing_BAO_MailingJob
::workflowClause();
321 $domainID = CRM_Core_Config
::domainID();
323 $modeClause = 'AND m.sms_provider_id IS NULL';
324 if ($mode == 'sms') {
325 $modeClause = 'AND m.sms_provider_id IS NOT NULL';
328 // Select all the mailing jobs that are created from
329 // when the mailing is submitted or scheduled.
334 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
338 AND ( ( j.start_date IS null
339 AND j.scheduled_date <= $currentTime
340 AND j.status = 'Scheduled'
341 AND j.end_date IS null ) )
342 AND ((j.job_type is NULL) OR (j.job_type <> 'child'))
343 ORDER BY j.scheduled_date,
348 // For each of the "Parent Jobs" we find, we split them into
349 // X Number of child jobs
350 while ($job->fetch()) {
351 // still use job level lock for each child job
352 $lock = Civi
::lockManager()->acquire("data.mailing.job.{$job->id}");
353 if (!$lock->isAcquired()) {
357 // Re-fetch the job status in case things
358 // changed between the first query and now
359 // to avoid race conditions
360 $job->status
= CRM_Core_DAO
::getFieldValue(
361 'CRM_Mailing_DAO_MailingJob',
367 if ($job->status
!= 'Scheduled') {
372 $transaction = new CRM_Core_Transaction();
374 $job->split_job($offset);
376 // Update the status of the parent job
377 self
::create(['id' => $job->id
, 'start_date' => date('YmdHis'), 'status' => 'Running']);
378 $transaction->commit();
380 // Release the job lock
386 * Split the parent job into n number of child job based on an offset.
387 * If null or 0 , we create only one child job
390 public function split_job($offset = 200) {
391 $recipient_count = CRM_Mailing_BAO_Recipients
::mailingSize($this->mailing_id
);
393 $jobTable = CRM_Mailing_DAO_MailingJob
::getTableName();
395 $dao = new CRM_Core_DAO();
398 INSERT INTO civicrm_mailing_job
399 (`mailing_id`, `scheduled_date`, `status`, `job_type`, `parent_id`, `job_offset`, `job_limit`)
400 VALUES (%1, %2, %3, %4, %5, %6, %7)
403 1 => array($this->mailing_id
, 'Integer'),
404 2 => array($this->scheduled_date
, 'String'),
405 3 => array('Scheduled', 'String'),
406 4 => array('child', 'String'),
407 5 => array($this->id
, 'Integer'),
408 6 => array(0, 'Integer'),
409 7 => array($recipient_count, 'Integer'),
412 // create one child job if the mailing size is less than the offset
413 // probably use a CRM_Mailing_DAO_MailingJob( );
414 if (empty($offset) ||
415 $recipient_count <= $offset
417 CRM_Core_DAO
::executeQuery($sql, $params);
420 // Creating 'child jobs'
421 $scheduled_unixtime = strtotime($this->scheduled_date
);
422 for ($i = 0, $s = 0; $i < $recipient_count; $i = $i +
$offset, $s++
) {
423 $params[2][0] = date('Y-m-d H:i:s', $scheduled_unixtime +
$s);
425 $params[7][0] = $offset;
426 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 // CRM-18543: there are situations when both the email and phone are null.
454 // Skip the recipient in this case.
455 if (empty($recipients->email_id
) && empty($recipients->phone_id
)) {
459 if ($recipients->phone_id
) {
460 $recipients->email_id
= "null";
463 $recipients->phone_id
= "null";
468 $recipients->email_id
,
469 $recipients->contact_id
,
470 $recipients->phone_id
,
473 if ($count % CRM_Mailing_Config
::BULK_MAIL_INSERT_COUNT
== 0) {
474 CRM_Mailing_Event_BAO_Queue
::bulkCreate($params, $now);
480 if (!empty($params)) {
481 CRM_Mailing_Event_BAO_Queue
::bulkCreate($params, $now);
490 * This is used by CiviMail but will be made redundant by FlexMailer.
491 * @param object $mailer
492 * A Mail object to send the messages.
494 * @param array $testParams
497 public function deliver(&$mailer, $testParams = NULL) {
498 if (\Civi
::settings()->get('experimentalFlexMailerEngine')) {
499 throw new \
RuntimeException("Cannot use legacy deliver() when experimentalFlexMailerEngine is enabled");
502 $mailing = new CRM_Mailing_BAO_Mailing();
503 $mailing->id
= $this->mailing_id
;
504 $mailing->find(TRUE);
509 if ($config == NULL) {
510 $config = CRM_Core_Config
::singleton();
513 if (property_exists($mailing, 'language') && $mailing->language
&& $mailing->language
!= 'en_US') {
514 $swapLang = CRM_Utils_AutoClean
::swap('global://dbLocale?getter', 'call://i18n/setLocale', $mailing->language
);
517 $job_date = CRM_Utils_Date
::isoToMysql($this->scheduled_date
);
520 if (!empty($testParams)) {
521 $mailing->subject
= ts('[CiviMail Draft]') . ' ' . $mailing->subject
;
524 CRM_Mailing_BAO_Mailing
::tokenReplace($mailing);
526 // get and format attachments
527 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_mailing', $mailing->id
);
529 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
530 CRM_Core_Smarty
::registerStringResource();
534 // This handles the edge case scenario where all the mails
535 // have been delivered in prior jobs.
538 // make sure that there's no more than $mailerBatchLimit mails processed in a run
539 $mailerBatchLimit = Civi
::settings()->get('mailerBatchLimit');
540 $eq = self
::findPendingTasks($this->id
, $mailing->sms_provider_id ?
'sms' : 'email');
541 while ($eq->fetch()) {
542 if ($mailerBatchLimit > 0 && self
::$mailsProcessed >= $mailerBatchLimit) {
543 if (!empty($fields)) {
544 $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
549 self
::$mailsProcessed++
;
554 'contact_id' => $eq->contact_id
,
555 'email' => $eq->email
,
556 'phone' => $eq->phone
,
558 if (count($fields) == self
::MAX_CONTACTS_TO_PROCESS
) {
559 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
570 if (!empty($fields)) {
571 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
578 * This is used by CiviMail but will be made redundant by FlexMailer.
579 * @param array $fields
580 * List of intended recipients.
581 * Each recipient is an array with keys 'hash', 'contact_id', 'email', etc.
585 * @param $attachments
590 public function deliverGroup(&$fields, &$mailing, &$mailer, &$job_date, &$attachments) {
591 static $smtpConnectionErrors = 0;
593 if (!is_object($mailer) ||
empty($fields)) {
594 CRM_Core_Error
::fatal();
597 // get the return properties
598 $returnProperties = $mailing->getReturnProperties();
599 $params = $targetParams = $deliveredParams = array();
603 // CRM-15702: Sending bulk sms to contacts without e-mail address fails.
604 // Solution is to skip checking for on hold
605 $skipOnHold = TRUE; //do include a statement to check wether e-mail address is on hold
606 if ($mailing->sms_provider_id
) {
607 $skipOnHold = FALSE; //do not include a statement to check wether e-mail address is on hold
610 foreach ($fields as $key => $field) {
611 $params[] = $field['contact_id'];
614 $details = CRM_Utils_Token
::getTokenDetails(
617 $skipOnHold, TRUE, NULL,
618 $mailing->getFlattenedTokens(),
623 $config = CRM_Core_Config
::singleton();
624 foreach ($fields as $key => $field) {
625 $contactID = $field['contact_id'];
626 if (!array_key_exists($contactID, $details[0])) {
627 $details[0][$contactID] = array();
630 // Compose the mailing.
631 $recipient = $replyToEmail = NULL;
632 $replyValue = strcmp($mailing->replyto_email
, $mailing->from_email
);
634 $replyToEmail = $mailing->replyto_email
;
637 $message = $mailing->compose(
638 $this->id
, $field['id'], $field['hash'],
639 $field['contact_id'], $field['email'],
640 $recipient, FALSE, $details[0][$contactID], $attachments,
641 FALSE, NULL, $replyToEmail
643 if (empty($message)) {
644 // lets keep the message in the queue
645 // most likely a permissions related issue with smarty templates
646 // or a bad contact id? CRM-9833
652 $body = $message->get();
653 $headers = $message->headers();
655 if ($mailing->sms_provider_id
) {
656 $provider = CRM_SMS_Provider
::singleton(array('mailing_id' => $mailing->id
));
657 $body = $provider->getMessage($message, $field['contact_id'], $details[0][$contactID]);
658 $headers = $provider->getRecipientDetails($field, $details[0][$contactID]);
661 // make $recipient actually be the *encoded* header, so as not to baffle Mail_RFC822, CRM-5743
662 $recipient = $headers['To'];
665 // disable error reporting on real mailings (but leave error reporting for tests), CRM-5744
667 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
670 $result = $mailer->send($recipient, $headers, $body, $this->id
);
676 if (is_a($result, 'PEAR_Error') && !$mailing->sms_provider_id
) {
678 $message = $result->getMessage();
679 if ($this->isTemporaryError($message)) {
680 // lets log this message and code
681 $code = $result->getCode();
682 CRM_Core_Error
::debug_log_message("SMTP Socket Error or failed to set sender error. Message: $message, Code: $code");
684 // these are socket write errors which most likely means smtp connection errors
685 // lets skip them and reconnect.
686 $smtpConnectionErrors++
;
687 if ($smtpConnectionErrors <= 5) {
688 $mailer->disconnect();
693 // seems like we have too many of them in a row, we should
694 // write stuff to disk and abort the cron job
702 CRM_Core_Error
::debug_log_message("Too many SMTP Socket Errors. Exiting");
703 CRM_Utils_System
::civiExit();
706 // Register the bounce event.
709 'event_queue_id' => $field['id'],
710 'job_id' => $this->id
,
711 'hash' => $field['hash'],
713 $params = array_merge($params,
714 CRM_Mailing_BAO_BouncePattern
::match($result->getMessage())
716 CRM_Mailing_Event_BAO_Bounce
::create($params);
718 elseif (is_a($result, 'PEAR_Error') && $mailing->sms_provider_id
) {
719 // Handle SMS errors: CRM-15426
720 $job_id = intval($this->id
);
721 $mailing_id = intval($mailing->id
);
722 CRM_Core_Error
::debug_log_message("Failed to send SMS message. Vars: mailing_id: ${mailing_id}, job_id: ${job_id}. Error message follows.");
723 CRM_Core_Error
::debug_log_message($result->getMessage());
726 // Register the delivery event.
727 $deliveredParams[] = $field['id'];
728 $targetParams[] = $field['contact_id'];
731 if ($count % CRM_Mailing_Config
::BULK_MAIL_INSERT_COUNT
== 0) {
740 // hack to stop mailing job at run time, CRM-4246.
741 // to avoid making too many DB calls for this rare case
742 // lets do it when we snapshot
743 $status = CRM_Core_DAO
::getFieldValue(
744 'CRM_Mailing_DAO_MailingJob',
751 if ($status != 'Running') {
759 // seems like a successful delivery or bounce, lets decrement error count
760 // only if we have smtp connection errors
761 if ($smtpConnectionErrors > 0) {
762 $smtpConnectionErrors--;
765 // If we have enabled the Throttle option, this is the time to enforce it.
766 $mailThrottleTime = Civi
::settings()->get('mailThrottleTime');
767 if (!empty($mailThrottleTime)) {
768 usleep((int ) $mailThrottleTime);
772 $result = $this->writeToDB(
787 * Determine if an SMTP error is temporary or permanent.
789 * @param string $message
790 * PEAR error message.
792 * TRUE - Temporary/retriable error
793 * FALSE - Permanent/non-retriable error
795 protected function isTemporaryError($message) {
796 // SMTP response code is buried in the message.
797 $code = preg_match('/ \(code: (.+), response: /', $message, $matches) ?
$matches[1] : '';
799 if (strpos($message, 'Failed to write to socket') !== FALSE) {
803 // Register 5xx SMTP response code (permanent failure) as bounce.
804 if (isset($code{0}) && $code{0} === '5') {
808 if (strpos($message, 'Failed to set sender') !== FALSE) {
812 if (strpos($message, 'Failed to add recipient') !== FALSE) {
816 if (strpos($message, 'Failed to send data') !== FALSE) {
826 * @param int $mailingId
827 * The id of the mailing to be canceled.
829 public static function cancel($mailingId) {
832 FROM civicrm_mailing_job
833 WHERE mailing_id = %1
835 AND ( ( job_type IS NULL ) OR
836 job_type <> 'child' )
838 $params = array(1 => array($mailingId, 'Integer'));
839 $job = CRM_Core_DAO
::executeQuery($sql, $params);
841 in_array($job->status
, array('Scheduled', 'Running', 'Paused'))
844 self
::create(['id' => $job->id
, 'end_date' => date('YmdHis'), 'status' => 'Canceled']);
846 // also cancel all child jobs
848 UPDATE civicrm_mailing_job
849 SET status = 'Canceled',
853 AND job_type = 'child'
854 AND status IN ( 'Scheduled', 'Running', 'Paused' )
857 1 => array($job->id
, 'Integer'),
858 2 => array(date('YmdHis'), 'Timestamp'),
860 CRM_Core_DAO
::executeQuery($sql, $params);
867 * @param int $mailingID
868 * The id of the mailing to be paused.
870 public static function pause($mailingID) {
872 UPDATE civicrm_mailing_job
873 SET status = 'Paused'
874 WHERE mailing_id = %1
876 AND status IN ('Scheduled', 'Running')
878 CRM_Core_DAO
::executeQuery($sql, array(1 => array($mailingID, 'Integer')));
884 * @param int $mailingID
885 * The id of the mailing to be resumed.
887 public static function resume($mailingID) {
889 UPDATE civicrm_mailing_job
890 SET status = 'Scheduled'
891 WHERE mailing_id = %1
893 AND start_date IS NULL
894 AND status = 'Paused'
896 CRM_Core_DAO
::executeQuery($sql, array(1 => array($mailingID, 'Integer')));
899 UPDATE civicrm_mailing_job
900 SET status = 'Running'
901 WHERE mailing_id = %1
903 AND start_date IS NOT NULL
904 AND status = 'Paused'
906 CRM_Core_DAO
::executeQuery($sql, array(1 => array($mailingID, 'Integer')));
910 * Return a translated status enum string.
912 * @param string $status
916 * The translated version
918 public static function status($status) {
919 static $translation = NULL;
921 if (empty($translation)) {
922 $translation = array(
923 'Scheduled' => ts('Scheduled'),
924 'Running' => ts('Running'),
925 'Complete' => ts('Complete'),
926 'Paused' => ts('Paused'),
927 'Canceled' => ts('Canceled'),
930 return CRM_Utils_Array
::value($status, $translation, ts('Not scheduled'));
934 * Return a workflow clause for use in SQL queries,
935 * to only process jobs that are approved.
938 * For use in a WHERE clause
940 public static function workflowClause() {
941 // add an additional check and only process
942 // jobs that are approved
943 if (CRM_Mailing_Info
::workflowEnabled()) {
944 $approveOptionID = CRM_Core_PseudoConstant
::getKey('CRM_Mailing_BAO_Mailing', 'approval_status_id', 'Approved');
945 if ($approveOptionID) {
946 return " AND m.approval_status_id = $approveOptionID ";
953 * @param array $deliveredParams
954 * @param array $targetParams
959 * @throws CRM_Core_Exception
962 public function writeToDB(
968 static $activityTypeID = NULL;
969 static $writeActivity = NULL;
971 if (!empty($deliveredParams)) {
972 CRM_Mailing_Event_BAO_Delivered
::bulkCreate($deliveredParams);
973 $deliveredParams = array();
976 if ($writeActivity === NULL) {
977 $writeActivity = Civi
::settings()->get('write_activity_record');
980 if (!$writeActivity) {
985 if (!empty($targetParams) && !empty($mailing->scheduled_id
)) {
986 if (!$activityTypeID) {
987 if ($mailing->sms_provider_id
) {
988 $mailing->subject
= $mailing->name
;
989 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Mass SMS'
993 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Bulk Email');
995 if (!$activityTypeID) {
996 CRM_Core_Error
::fatal();
1001 'source_contact_id' => $mailing->scheduled_id
,
1003 'target_contact_id' => array_unique($targetParams),
1004 'activity_type_id' => $activityTypeID,
1005 'source_record_id' => $this->mailing_id
,
1006 'activity_date_time' => $job_date,
1007 'subject' => $mailing->subject
,
1009 'deleteActivityTarget' => FALSE,
1010 'campaign_id' => $mailing->campaign_id
,
1013 //check whether activity is already created for this mailing.
1014 //if yes then create only target contact record.
1017 FROM civicrm_activity
1018 WHERE civicrm_activity.activity_type_id = %1
1019 AND civicrm_activity.source_record_id = %2
1022 $queryParams = array(
1023 1 => array($activityTypeID, 'Integer'),
1024 2 => array($this->mailing_id
, 'Integer'),
1026 $activityID = CRM_Core_DAO
::singleValueQuery($query, $queryParams);
1029 $activity['id'] = $activityID;
1032 if (CRM_Core_BAO_Email
::isMultipleBulkMail()) {
1033 static $targetRecordID = NULL;
1034 if (!$targetRecordID) {
1035 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
1036 $targetRecordID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1039 // make sure we don't attempt to duplicate the target activity
1040 foreach ($activity['target_contact_id'] as $key => $targetID) {
1043 FROM civicrm_activity_contact
1044 WHERE activity_id = $activityID
1045 AND contact_id = $targetID
1046 AND record_type_id = $targetRecordID
1048 if (CRM_Core_DAO
::singleValueQuery($sql)) {
1049 unset($activity['target_contact_id'][$key]);
1055 if (is_a(CRM_Activity_BAO_Activity
::create($activity), 'CRM_Core_Error')) {
1059 $targetParams = array();
1066 * Search the mailing-event queue for a list of pending delivery tasks.
1069 * @param string $medium
1070 * Ex: 'email' or 'sms'.
1072 * @return \CRM_Mailing_Event_BAO_Queue
1073 * A query object whose rows provide ('id', 'contact_id', 'hash') and ('email' or 'phone').
1075 public static function findPendingTasks($jobId, $medium) {
1076 $eq = new CRM_Mailing_Event_BAO_Queue();
1077 $queueTable = CRM_Mailing_Event_BAO_Queue
::getTableName();
1078 $emailTable = CRM_Core_BAO_Email
::getTableName();
1079 $phoneTable = CRM_Core_BAO_Phone
::getTableName();
1080 $contactTable = CRM_Contact_BAO_Contact
::getTableName();
1081 $deliveredTable = CRM_Mailing_Event_BAO_Delivered
::getTableName();
1082 $bounceTable = CRM_Mailing_Event_BAO_Bounce
::getTableName();
1084 $query = " SELECT $queueTable.id,
1085 $emailTable.email as email,
1086 $queueTable.contact_id,
1090 INNER JOIN $emailTable
1091 ON $queueTable.email_id = $emailTable.id
1092 INNER JOIN $contactTable
1093 ON $contactTable.id = $emailTable.contact_id
1094 LEFT JOIN $deliveredTable
1095 ON $queueTable.id = $deliveredTable.event_queue_id
1096 LEFT JOIN $bounceTable
1097 ON $queueTable.id = $bounceTable.event_queue_id
1098 WHERE $queueTable.job_id = " . $jobId . "
1099 AND $deliveredTable.id IS null
1100 AND $bounceTable.id IS null
1101 AND $contactTable.is_opt_out = 0";
1103 if ($medium === 'sms') {
1105 SELECT $queueTable.id,
1106 $phoneTable.phone as phone,
1107 $queueTable.contact_id,
1111 INNER JOIN $phoneTable
1112 ON $queueTable.phone_id = $phoneTable.id
1113 INNER JOIN $contactTable
1114 ON $contactTable.id = $phoneTable.contact_id
1115 LEFT JOIN $deliveredTable
1116 ON $queueTable.id = $deliveredTable.event_queue_id
1117 LEFT JOIN $bounceTable
1118 ON $queueTable.id = $bounceTable.event_queue_id
1119 WHERE $queueTable.job_id = " . $jobId . "
1120 AND $deliveredTable.id IS null
1121 AND $bounceTable.id IS null
1122 AND ( $contactTable.is_opt_out = 0
1123 OR $contactTable.do_not_sms = 0 )";
1130 * Delete the mailing job.
1137 public static function del($id) {
1138 CRM_Utils_Hook
::pre('delete', 'MailingJob', $id, CRM_Core_DAO
::$_nullArray);
1140 $jobDAO = new CRM_Mailing_BAO_MailingJob();
1142 $result = $jobDAO->delete();
1144 CRM_Utils_Hook
::post('delete', 'MailingJob', $jobDAO->id
, $jobDAO);