Merge pull request #10834 from jitendrapurohit/CRM-20999
[civicrm-core.git] / CRM / Mailing / BAO / MailingJob.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2017
32 */
33
34 require_once 'Mail.php';
35
36 /**
37 * Class CRM_Mailing_BAO_MailingJob
38 */
39 class CRM_Mailing_BAO_MailingJob extends CRM_Mailing_DAO_MailingJob {
40 const MAX_CONTACTS_TO_PROCESS = 1000;
41
42 /**
43 * (Dear God Why) Keep a global count of mails processed within the current
44 * request.
45 *
46 * @var int
47 */
48 static $mailsProcessed = 0;
49
50 /**
51 * Class constructor.
52 */
53 public function __construct() {
54 parent::__construct();
55 }
56
57 /**
58 * Create mailing job.
59 *
60 * @param array $params
61 *
62 * @return \CRM_Mailing_BAO_MailingJob
63 * @throws \CRM_Core_Exception
64 */
65 static public function create($params) {
66 $job = new CRM_Mailing_BAO_MailingJob();
67 $job->mailing_id = $params['mailing_id'];
68 $job->status = $params['status'];
69 $job->scheduled_date = $params['scheduled_date'];
70 $job->is_test = $params['is_test'];
71 $job->save();
72 $mailing = new CRM_Mailing_BAO_Mailing();
73 $mailing->id = $params['mailing_id'];
74 if ($mailing->id && $mailing->find(TRUE)) {
75 $mailing->getRecipients($job->id, $params['mailing_id'], TRUE, $mailing->dedupe_email);
76 return $job;
77 }
78 else {
79 throw new CRM_Core_Exception("Failed to create job: Unknown mailing ID");
80 }
81 }
82
83 /**
84 * Initiate all pending/ready jobs.
85 *
86 * @param array $testParams
87 * @param string $mode
88 *
89 * @return bool|null
90 */
91 public static function runJobs($testParams = NULL, $mode = NULL) {
92 $job = new CRM_Mailing_BAO_MailingJob();
93
94 $config = CRM_Core_Config::singleton();
95 $jobTable = CRM_Mailing_DAO_MailingJob::getTableName();
96 $mailingTable = CRM_Mailing_DAO_Mailing::getTableName();
97 $mailerBatchLimit = Civi::settings()->get('mailerBatchLimit');
98
99 if (!empty($testParams)) {
100 $query = "
101 SELECT *
102 FROM $jobTable
103 WHERE id = {$testParams['job_id']}";
104 $job->query($query);
105 }
106 else {
107 $currentTime = date('YmdHis');
108 $mailingACL = CRM_Mailing_BAO_Mailing::mailingACL('m');
109 $domainID = CRM_Core_Config::domainID();
110
111 $modeClause = 'AND m.sms_provider_id IS NULL';
112 if ($mode == 'sms') {
113 $modeClause = 'AND m.sms_provider_id IS NOT NULL';
114 }
115
116 // Select the first child job that is scheduled
117 // CRM-6835
118 $query = "
119 SELECT j.*
120 FROM $jobTable j,
121 $mailingTable m
122 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
123 {$modeClause}
124 AND j.is_test = 0
125 AND ( ( j.start_date IS null
126 AND j.scheduled_date <= $currentTime
127 AND j.status = 'Scheduled' )
128 OR ( j.status = 'Running'
129 AND j.end_date IS null ) )
130 AND (j.job_type = 'child')
131 AND {$mailingACL}
132 ORDER BY j.scheduled_date ASC,
133 j.id
134 ";
135
136 $job->query($query);
137 }
138
139 while ($job->fetch()) {
140 // still use job level lock for each child job
141 $lock = Civi::lockManager()->acquire("data.mailing.job.{$job->id}");
142 if (!$lock->isAcquired()) {
143 continue;
144 }
145
146 // for test jobs we do not change anything, since its on a short-circuit path
147 if (empty($testParams)) {
148 // we've got the lock, but while we were waiting and processing
149 // other emails, this job might have changed under us
150 // lets get the job status again and check
151 $job->status = CRM_Core_DAO::getFieldValue(
152 'CRM_Mailing_DAO_MailingJob',
153 $job->id,
154 'status',
155 'id',
156 TRUE
157 );
158
159 if (
160 $job->status != 'Running' &&
161 $job->status != 'Scheduled'
162 ) {
163 // this includes Cancelled and other statuses, CRM-4246
164 $lock->release();
165 continue;
166 }
167 }
168
169 /* Queue up recipients for the child job being launched */
170
171 if ($job->status != 'Running') {
172 $transaction = new CRM_Core_Transaction();
173
174 // have to queue it up based on the offset and limits
175 // get the parent ID, and limit and offset
176 $job->queue($testParams);
177
178 // Mark up the starting time
179 $saveJob = new CRM_Mailing_DAO_MailingJob();
180 $saveJob->id = $job->id;
181 $saveJob->start_date = date('YmdHis');
182 $saveJob->status = 'Running';
183 $saveJob->save();
184
185 $transaction->commit();
186 }
187
188 // Get the mailer
189 if ($mode === NULL) {
190 $mailer = \Civi::service('pear_mail');
191 }
192 elseif ($mode == 'sms') {
193 $mailer = CRM_SMS_Provider::singleton(array('mailing_id' => $job->mailing_id));
194 }
195
196 // Compose and deliver each child job
197 if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_DELIVER')) {
198 $isComplete = Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_DELIVER, array($job, $mailer, $testParams));
199 }
200 else {
201 $isComplete = $job->deliver($mailer, $testParams);
202 }
203
204 CRM_Utils_Hook::post('create', 'CRM_Mailing_DAO_Spool', $job->id, $isComplete);
205
206 // Mark the child complete
207 if ($isComplete) {
208 // Finish the job.
209
210 $transaction = new CRM_Core_Transaction();
211
212 $saveJob = new CRM_Mailing_DAO_MailingJob();
213 $saveJob->id = $job->id;
214 $saveJob->end_date = date('YmdHis');
215 $saveJob->status = 'Complete';
216 $saveJob->save();
217
218 $transaction->commit();
219
220 // don't mark the mailing as complete
221 }
222
223 // Release the child joblock
224 $lock->release();
225
226 if ($testParams) {
227 return $isComplete;
228 }
229
230 // CRM-17629: Stop processing jobs if mailer batch limit reached
231 if ($mailerBatchLimit > 0 && self::$mailsProcessed >= $mailerBatchLimit) {
232 break;
233 }
234
235 }
236 }
237
238 /**
239 * Post process to determine if the parent job
240 * as well as the mailing is complete after the run.
241 * @param null $mode
242 */
243 public static function runJobs_post($mode = NULL) {
244
245 $job = new CRM_Mailing_BAO_MailingJob();
246
247 $mailing = new CRM_Mailing_BAO_Mailing();
248
249 $config = CRM_Core_Config::singleton();
250 $jobTable = CRM_Mailing_DAO_MailingJob::getTableName();
251 $mailingTable = CRM_Mailing_DAO_Mailing::getTableName();
252
253 $currentTime = date('YmdHis');
254 $mailingACL = CRM_Mailing_BAO_Mailing::mailingACL('m');
255 $domainID = CRM_Core_Config::domainID();
256
257 $query = "
258 SELECT j.*
259 FROM $jobTable j,
260 $mailingTable m
261 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
262 AND j.is_test = 0
263 AND j.scheduled_date <= $currentTime
264 AND j.status = 'Running'
265 AND j.end_date IS null
266 AND (j.job_type != 'child' OR j.job_type is NULL)
267 ORDER BY j.scheduled_date,
268 j.start_date";
269
270 $job->query($query);
271
272 // For each parent job that is running, let's look at their child jobs
273 while ($job->fetch()) {
274
275 $child_job = new CRM_Mailing_BAO_MailingJob();
276
277 $child_job_sql = "
278 SELECT count(j.id)
279 FROM civicrm_mailing_job j, civicrm_mailing m
280 WHERE m.id = j.mailing_id
281 AND j.job_type = 'child'
282 AND j.parent_id = %1
283 AND j.status <> 'Complete'";
284 $params = array(1 => array($job->id, 'Integer'));
285
286 $anyChildLeft = CRM_Core_DAO::singleValueQuery($child_job_sql, $params);
287
288 // all of the child jobs are complete, update
289 // the parent job as well as the mailing status
290 if (!$anyChildLeft) {
291
292 $transaction = new CRM_Core_Transaction();
293
294 $saveJob = new CRM_Mailing_DAO_MailingJob();
295 $saveJob->id = $job->id;
296 $saveJob->end_date = date('YmdHis');
297 $saveJob->status = 'Complete';
298 $saveJob->save();
299
300 $mailing->reset();
301 $mailing->id = $job->mailing_id;
302 $mailing->is_completed = TRUE;
303 $mailing->save();
304 $transaction->commit();
305
306 // CRM-17763
307 CRM_Utils_Hook::postMailing($job->mailing_id);
308 }
309 }
310 }
311
312
313 /**
314 * before we run jobs, we need to split the jobs
315 * @param int $offset
316 * @param null $mode
317 */
318 public static function runJobs_pre($offset = 200, $mode = NULL) {
319 $job = new CRM_Mailing_BAO_MailingJob();
320
321 $jobTable = CRM_Mailing_DAO_MailingJob::getTableName();
322 $mailingTable = CRM_Mailing_DAO_Mailing::getTableName();
323
324 $currentTime = date('YmdHis');
325 $mailingACL = CRM_Mailing_BAO_Mailing::mailingACL('m');
326
327 $workflowClause = CRM_Mailing_BAO_MailingJob::workflowClause();
328
329 $domainID = CRM_Core_Config::domainID();
330
331 $modeClause = 'AND m.sms_provider_id IS NULL';
332 if ($mode == 'sms') {
333 $modeClause = 'AND m.sms_provider_id IS NOT NULL';
334 }
335
336 // Select all the mailing jobs that are created from
337 // when the mailing is submitted or scheduled.
338 $query = "
339 SELECT j.*
340 FROM $jobTable j,
341 $mailingTable m
342 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
343 $workflowClause
344 $modeClause
345 AND j.is_test = 0
346 AND ( ( j.start_date IS null
347 AND j.scheduled_date <= $currentTime
348 AND j.status = 'Scheduled'
349 AND j.end_date IS null ) )
350 AND ((j.job_type is NULL) OR (j.job_type <> 'child'))
351 ORDER BY j.scheduled_date,
352 j.start_date";
353
354 $job->query($query);
355
356 // For each of the "Parent Jobs" we find, we split them into
357 // X Number of child jobs
358 while ($job->fetch()) {
359 // still use job level lock for each child job
360 $lock = Civi::lockManager()->acquire("data.mailing.job.{$job->id}");
361 if (!$lock->isAcquired()) {
362 continue;
363 }
364
365 // Re-fetch the job status in case things
366 // changed between the first query and now
367 // to avoid race conditions
368 $job->status = CRM_Core_DAO::getFieldValue(
369 'CRM_Mailing_DAO_MailingJob',
370 $job->id,
371 'status',
372 'id',
373 TRUE
374 );
375 if ($job->status != 'Scheduled') {
376 $lock->release();
377 continue;
378 }
379
380 $job->split_job($offset);
381
382 // update the status of the parent job
383 $transaction = new CRM_Core_Transaction();
384
385 $saveJob = new CRM_Mailing_DAO_MailingJob();
386 $saveJob->id = $job->id;
387 $saveJob->start_date = date('YmdHis');
388 $saveJob->status = 'Running';
389 $saveJob->save();
390
391 $transaction->commit();
392
393 // Release the job lock
394 $lock->release();
395 }
396 }
397
398 /**
399 * Split the parent job into n number of child job based on an offset.
400 * If null or 0 , we create only one child job
401 * @param int $offset
402 */
403 public function split_job($offset = 200) {
404 $recipient_count = CRM_Mailing_BAO_Recipients::mailingSize($this->mailing_id);
405
406 $jobTable = CRM_Mailing_DAO_MailingJob::getTableName();
407
408 $dao = new CRM_Core_DAO();
409
410 $sql = "
411 INSERT INTO civicrm_mailing_job
412 (`mailing_id`, `scheduled_date`, `status`, `job_type`, `parent_id`, `job_offset`, `job_limit`)
413 VALUES (%1, %2, %3, %4, %5, %6, %7)
414 ";
415 $params = array(
416 1 => array($this->mailing_id, 'Integer'),
417 2 => array($this->scheduled_date, 'String'),
418 3 => array('Scheduled', 'String'),
419 4 => array('child', 'String'),
420 5 => array($this->id, 'Integer'),
421 6 => array(0, 'Integer'),
422 7 => array($recipient_count, 'Integer'),
423 );
424
425 // create one child job if the mailing size is less than the offset
426 // probably use a CRM_Mailing_DAO_MailingJob( );
427 if (empty($offset) ||
428 $recipient_count <= $offset
429 ) {
430 CRM_Core_DAO::executeQuery($sql, $params);
431 }
432 else {
433 // Creating 'child jobs'
434 $scheduled_unixtime = strtotime($this->scheduled_date);
435 for ($i = 0, $s = 0; $i < $recipient_count; $i = $i + $offset, $s++) {
436 $params[2][0] = date('Y-m-d H:i:s', $scheduled_unixtime + $s);
437 $params[6][0] = $i;
438 $params[7][0] = $offset;
439 CRM_Core_DAO::executeQuery($sql, $params);
440 }
441 }
442 }
443
444 /**
445 * @param array $testParams
446 */
447 public function queue($testParams = NULL) {
448 $mailing = new CRM_Mailing_BAO_Mailing();
449 $mailing->id = $this->mailing_id;
450 if (!empty($testParams)) {
451 $mailing->getTestRecipients($testParams);
452 }
453 else {
454 // We are still getting all the recipients from the parent job
455 // so we don't mess with the include/exclude logic.
456 $recipients = CRM_Mailing_BAO_Recipients::mailingQuery($this->mailing_id, $this->job_offset, $this->job_limit);
457
458 // FIXME: this is not very smart, we should move this to one DB call
459 // INSERT INTO ... SELECT FROM ..
460 // the thing we need to figure out is how to generate the hash automatically
461 $now = time();
462 $params = array();
463 $count = 0;
464 while ($recipients->fetch()) {
465 // CRM-18543: there are situations when both the email and phone are null.
466 // Skip the recipient in this case.
467 if (empty($recipients->email_id) && empty($recipients->phone_id)) {
468 continue;
469 }
470
471 if ($recipients->phone_id) {
472 $recipients->email_id = "null";
473 }
474 else {
475 $recipients->phone_id = "null";
476 }
477
478 $params[] = array(
479 $this->id,
480 $recipients->email_id,
481 $recipients->contact_id,
482 $recipients->phone_id,
483 );
484 $count++;
485 if ($count % CRM_Mailing_Config::BULK_MAIL_INSERT_COUNT == 0) {
486 CRM_Mailing_Event_BAO_Queue::bulkCreate($params, $now);
487 $count = 0;
488 $params = array();
489 }
490 }
491
492 if (!empty($params)) {
493 CRM_Mailing_Event_BAO_Queue::bulkCreate($params, $now);
494 }
495 }
496 }
497
498 /**
499 * Send the mailing.
500 *
501 * @param object $mailer
502 * A Mail object to send the messages.
503 *
504 * @param array $testParams
505 */
506 public function deliver(&$mailer, $testParams = NULL) {
507 if (\Civi::settings()->get('experimentalFlexMailerEngine')) {
508 throw new \RuntimeException("Cannot use legacy deliver() when experimentalFlexMailerEngine is enabled");
509 }
510
511 $mailing = new CRM_Mailing_BAO_Mailing();
512 $mailing->id = $this->mailing_id;
513 $mailing->find(TRUE);
514 $mailing->free();
515
516 $config = NULL;
517
518 if ($config == NULL) {
519 $config = CRM_Core_Config::singleton();
520 }
521
522 if (property_exists($mailing, 'language') && $mailing->language && $mailing->language != 'en_US') {
523 $swapLang = CRM_Utils_AutoClean::swap('global://dbLocale?getter', 'call://i18n/setLocale', $mailing->language);
524 }
525
526 $job_date = CRM_Utils_Date::isoToMysql($this->scheduled_date);
527 $fields = array();
528
529 if (!empty($testParams)) {
530 $mailing->subject = ts('[CiviMail Draft]') . ' ' . $mailing->subject;
531 }
532
533 CRM_Mailing_BAO_Mailing::tokenReplace($mailing);
534
535 // get and format attachments
536 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_mailing', $mailing->id);
537
538 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
539 CRM_Core_Smarty::registerStringResource();
540 }
541
542 // CRM-12376
543 // This handles the edge case scenario where all the mails
544 // have been delivered in prior jobs.
545 $isDelivered = TRUE;
546
547 // make sure that there's no more than $mailerBatchLimit mails processed in a run
548 $mailerBatchLimit = Civi::settings()->get('mailerBatchLimit');
549 $eq = self::findPendingTasks($this->id, $mailing->sms_provider_id ? 'sms' : 'email');
550 while ($eq->fetch()) {
551 if ($mailerBatchLimit > 0 && self::$mailsProcessed >= $mailerBatchLimit) {
552 if (!empty($fields)) {
553 $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
554 }
555 $eq->free();
556 return FALSE;
557 }
558 self::$mailsProcessed++;
559
560 $fields[] = array(
561 'id' => $eq->id,
562 'hash' => $eq->hash,
563 'contact_id' => $eq->contact_id,
564 'email' => $eq->email,
565 'phone' => $eq->phone,
566 );
567 if (count($fields) == self::MAX_CONTACTS_TO_PROCESS) {
568 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
569 if (!$isDelivered) {
570 $eq->free();
571 return $isDelivered;
572 }
573 $fields = array();
574 }
575 }
576
577 $eq->free();
578
579 if (!empty($fields)) {
580 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
581 }
582 return $isDelivered;
583 }
584
585 /**
586 * @param array $fields
587 * List of intended recipients.
588 * Each recipient is an array with keys 'hash', 'contact_id', 'email', etc.
589 * @param $mailing
590 * @param $mailer
591 * @param $job_date
592 * @param $attachments
593 *
594 * @return bool|null
595 * @throws Exception
596 */
597 public function deliverGroup(&$fields, &$mailing, &$mailer, &$job_date, &$attachments) {
598 static $smtpConnectionErrors = 0;
599
600 if (!is_object($mailer) || empty($fields)) {
601 CRM_Core_Error::fatal();
602 }
603
604 // get the return properties
605 $returnProperties = $mailing->getReturnProperties();
606 $params = $targetParams = $deliveredParams = array();
607 $count = 0;
608
609 // CRM-15702: Sending bulk sms to contacts without e-mail address fails.
610 // Solution is to skip checking for on hold
611 $skipOnHold = TRUE; //do include a statement to check wether e-mail address is on hold
612 if ($mailing->sms_provider_id) {
613 $skipOnHold = FALSE; //do not include a statement to check wether e-mail address is on hold
614 }
615
616 foreach ($fields as $key => $field) {
617 $params[] = $field['contact_id'];
618 }
619
620 $details = CRM_Utils_Token::getTokenDetails(
621 $params,
622 $returnProperties,
623 $skipOnHold, TRUE, NULL,
624 $mailing->getFlattenedTokens(),
625 get_class($this),
626 $this->id
627 );
628
629 $config = CRM_Core_Config::singleton();
630 foreach ($fields as $key => $field) {
631 $contactID = $field['contact_id'];
632 if (!array_key_exists($contactID, $details[0])) {
633 $details[0][$contactID] = array();
634 }
635
636 // Compose the mailing.
637 $recipient = $replyToEmail = NULL;
638 $replyValue = strcmp($mailing->replyto_email, $mailing->from_email);
639 if ($replyValue) {
640 $replyToEmail = $mailing->replyto_email;
641 }
642
643 $message = $mailing->compose(
644 $this->id, $field['id'], $field['hash'],
645 $field['contact_id'], $field['email'],
646 $recipient, FALSE, $details[0][$contactID], $attachments,
647 FALSE, NULL, $replyToEmail
648 );
649 if (empty($message)) {
650 // lets keep the message in the queue
651 // most likely a permissions related issue with smarty templates
652 // or a bad contact id? CRM-9833
653 continue;
654 }
655
656 // Send the mailing.
657
658 $body = &$message->get();
659 $headers = &$message->headers();
660
661 if ($mailing->sms_provider_id) {
662 $provider = CRM_SMS_Provider::singleton(array('mailing_id' => $mailing->id));
663 $body = $provider->getMessage($message, $field['contact_id'], $details[0][$contactID]);
664 $headers = $provider->getRecipientDetails($field, $details[0][$contactID]);
665 }
666
667 // make $recipient actually be the *encoded* header, so as not to baffle Mail_RFC822, CRM-5743
668 $recipient = $headers['To'];
669 $result = NULL;
670
671 // disable error reporting on real mailings (but leave error reporting for tests), CRM-5744
672 if ($job_date) {
673 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
674 }
675
676 $result = $mailer->send($recipient, $headers, $body, $this->id);
677
678 if ($job_date) {
679 unset($errorScope);
680 }
681
682 if (is_a($result, 'PEAR_Error') && !$mailing->sms_provider_id) {
683 // CRM-9191
684 $message = $result->getMessage();
685 if (
686 strpos($message, 'Failed to write to socket') !== FALSE ||
687 strpos($message, 'Failed to set sender') !== FALSE
688 ) {
689 // lets log this message and code
690 $code = $result->getCode();
691 CRM_Core_Error::debug_log_message("SMTP Socket Error or failed to set sender error. Message: $message, Code: $code");
692
693 // these are socket write errors which most likely means smtp connection errors
694 // lets skip them
695 $smtpConnectionErrors++;
696 if ($smtpConnectionErrors <= 5) {
697 continue;
698 }
699
700 // seems like we have too many of them in a row, we should
701 // write stuff to disk and abort the cron job
702 $this->writeToDB(
703 $deliveredParams,
704 $targetParams,
705 $mailing,
706 $job_date
707 );
708
709 CRM_Core_Error::debug_log_message("Too many SMTP Socket Errors. Exiting");
710 CRM_Utils_System::civiExit();
711 }
712
713 // Register the bounce event.
714
715 $params = array(
716 'event_queue_id' => $field['id'],
717 'job_id' => $this->id,
718 'hash' => $field['hash'],
719 );
720 $params = array_merge($params,
721 CRM_Mailing_BAO_BouncePattern::match($result->getMessage())
722 );
723 CRM_Mailing_Event_BAO_Bounce::create($params);
724 }
725 elseif (is_a($result, 'PEAR_Error') && $mailing->sms_provider_id) {
726 // Handle SMS errors: CRM-15426
727 $job_id = intval($this->id);
728 $mailing_id = intval($mailing->id);
729 CRM_Core_Error::debug_log_message("Failed to send SMS message. Vars: mailing_id: ${mailing_id}, job_id: ${job_id}. Error message follows.");
730 CRM_Core_Error::debug_log_message($result->getMessage());
731 }
732 else {
733 // Register the delivery event.
734 $deliveredParams[] = $field['id'];
735 $targetParams[] = $field['contact_id'];
736
737 $count++;
738 if ($count % CRM_Mailing_Config::BULK_MAIL_INSERT_COUNT == 0) {
739 $this->writeToDB(
740 $deliveredParams,
741 $targetParams,
742 $mailing,
743 $job_date
744 );
745 $count = 0;
746
747 // hack to stop mailing job at run time, CRM-4246.
748 // to avoid making too many DB calls for this rare case
749 // lets do it when we snapshot
750 $status = CRM_Core_DAO::getFieldValue(
751 'CRM_Mailing_DAO_MailingJob',
752 $this->id,
753 'status',
754 'id',
755 TRUE
756 );
757
758 if ($status != 'Running') {
759 return FALSE;
760 }
761 }
762 }
763
764 unset($result);
765
766 // seems like a successful delivery or bounce, lets decrement error count
767 // only if we have smtp connection errors
768 if ($smtpConnectionErrors > 0) {
769 $smtpConnectionErrors--;
770 }
771
772 // If we have enabled the Throttle option, this is the time to enforce it.
773 $mailThrottleTime = Civi::settings()->get('mailThrottleTime');
774 if (!empty($mailThrottleTime)) {
775 usleep((int ) $mailThrottleTime);
776 }
777 }
778
779 $result = $this->writeToDB(
780 $deliveredParams,
781 $targetParams,
782 $mailing,
783 $job_date
784 );
785
786 return $result;
787 }
788
789 /**
790 * Cancel a mailing.
791 *
792 * @param int $mailingId
793 * The id of the mailing to be canceled.
794 */
795 public static function cancel($mailingId) {
796 $sql = "
797 SELECT *
798 FROM civicrm_mailing_job
799 WHERE mailing_id = %1
800 AND is_test = 0
801 AND ( ( job_type IS NULL ) OR
802 job_type <> 'child' )
803 ";
804 $params = array(1 => array($mailingId, 'Integer'));
805 $job = CRM_Core_DAO::executeQuery($sql, $params);
806 if ($job->fetch() &&
807 in_array($job->status, array('Scheduled', 'Running', 'Paused'))
808 ) {
809
810 $newJob = new CRM_Mailing_BAO_MailingJob();
811 $newJob->id = $job->id;
812 $newJob->end_date = date('YmdHis');
813 $newJob->status = 'Canceled';
814 $newJob->save();
815
816 // also cancel all child jobs
817 $sql = "
818 UPDATE civicrm_mailing_job
819 SET status = 'Canceled',
820 end_date = %2
821 WHERE parent_id = %1
822 AND is_test = 0
823 AND job_type = 'child'
824 AND status IN ( 'Scheduled', 'Running', 'Paused' )
825 ";
826 $params = array(
827 1 => array($job->id, 'Integer'),
828 2 => array(date('YmdHis'), 'Timestamp'),
829 );
830 CRM_Core_DAO::executeQuery($sql, $params);
831
832 CRM_Core_Session::setStatus(ts('The mailing has been canceled.'), ts('Canceled'), 'success');
833 }
834 }
835
836 /**
837 * Return a translated status enum string.
838 *
839 * @param string $status
840 * The status enum.
841 *
842 * @return string
843 * The translated version
844 */
845 public static function status($status) {
846 static $translation = NULL;
847
848 if (empty($translation)) {
849 $translation = array(
850 'Scheduled' => ts('Scheduled'),
851 'Running' => ts('Running'),
852 'Complete' => ts('Complete'),
853 'Paused' => ts('Paused'),
854 'Canceled' => ts('Canceled'),
855 );
856 }
857 return CRM_Utils_Array::value($status, $translation, ts('Not scheduled'));
858 }
859
860 /**
861 * Return a workflow clause for use in SQL queries,
862 * to only process jobs that are approved.
863 *
864 * @return string
865 * For use in a WHERE clause
866 */
867 public static function workflowClause() {
868 // add an additional check and only process
869 // jobs that are approved
870 if (CRM_Mailing_Info::workflowEnabled()) {
871 $approveOptionID = CRM_Core_OptionGroup::getValue('mail_approval_status',
872 'Approved',
873 'name'
874 );
875 if ($approveOptionID) {
876 return " AND m.approval_status_id = $approveOptionID ";
877 }
878 }
879 return '';
880 }
881
882 /**
883 * @param array $deliveredParams
884 * @param array $targetParams
885 * @param $mailing
886 * @param $job_date
887 *
888 * @return bool
889 * @throws CRM_Core_Exception
890 * @throws Exception
891 */
892 public function writeToDB(
893 &$deliveredParams,
894 &$targetParams,
895 &$mailing,
896 $job_date
897 ) {
898 static $activityTypeID = NULL;
899 static $writeActivity = NULL;
900
901 if (!empty($deliveredParams)) {
902 CRM_Mailing_Event_BAO_Delivered::bulkCreate($deliveredParams);
903 $deliveredParams = array();
904 }
905
906 if ($writeActivity === NULL) {
907 $writeActivity = Civi::settings()->get('write_activity_record');
908 }
909
910 if (!$writeActivity) {
911 return TRUE;
912 }
913
914 $result = TRUE;
915 if (!empty($targetParams) && !empty($mailing->scheduled_id)) {
916 if (!$activityTypeID) {
917 if ($mailing->sms_provider_id) {
918 $mailing->subject = $mailing->name;
919 $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Mass SMS'
920 );
921 }
922 else {
923 $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Bulk Email');
924 }
925 if (!$activityTypeID) {
926 CRM_Core_Error::fatal();
927 }
928 }
929
930 $activity = array(
931 'source_contact_id' => $mailing->scheduled_id,
932 // CRM-9519
933 'target_contact_id' => array_unique($targetParams),
934 'activity_type_id' => $activityTypeID,
935 'source_record_id' => $this->mailing_id,
936 'activity_date_time' => $job_date,
937 'subject' => $mailing->subject,
938 'status_id' => 2,
939 'deleteActivityTarget' => FALSE,
940 'campaign_id' => $mailing->campaign_id,
941 );
942
943 //check whether activity is already created for this mailing.
944 //if yes then create only target contact record.
945 $query = "
946 SELECT id
947 FROM civicrm_activity
948 WHERE civicrm_activity.activity_type_id = %1
949 AND civicrm_activity.source_record_id = %2
950 ";
951
952 $queryParams = array(
953 1 => array($activityTypeID, 'Integer'),
954 2 => array($this->mailing_id, 'Integer'),
955 );
956 $activityID = CRM_Core_DAO::singleValueQuery($query, $queryParams);
957
958 if ($activityID) {
959 $activity['id'] = $activityID;
960
961 // CRM-9519
962 if (CRM_Core_BAO_Email::isMultipleBulkMail()) {
963 static $targetRecordID = NULL;
964 if (!$targetRecordID) {
965 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
966 $targetRecordID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
967 }
968
969 // make sure we don't attempt to duplicate the target activity
970 foreach ($activity['target_contact_id'] as $key => $targetID) {
971 $sql = "
972 SELECT id
973 FROM civicrm_activity_contact
974 WHERE activity_id = $activityID
975 AND contact_id = $targetID
976 AND record_type_id = $targetRecordID
977 ";
978 if (CRM_Core_DAO::singleValueQuery($sql)) {
979 unset($activity['target_contact_id'][$key]);
980 }
981 }
982 }
983 }
984
985 if (is_a(CRM_Activity_BAO_Activity::create($activity), 'CRM_Core_Error')) {
986 $result = FALSE;
987 }
988
989 $targetParams = array();
990 }
991
992 return $result;
993 }
994
995 /**
996 * Search the mailing-event queue for a list of pending delivery tasks.
997 *
998 * @param int $jobId
999 * @param string $medium
1000 * Ex: 'email' or 'sms'.
1001 *
1002 * @return \CRM_Mailing_Event_BAO_Queue
1003 * A query object whose rows provide ('id', 'contact_id', 'hash') and ('email' or 'phone').
1004 */
1005 public static function findPendingTasks($jobId, $medium) {
1006 $eq = new CRM_Mailing_Event_BAO_Queue();
1007 $queueTable = CRM_Mailing_Event_BAO_Queue::getTableName();
1008 $emailTable = CRM_Core_BAO_Email::getTableName();
1009 $phoneTable = CRM_Core_BAO_Phone::getTableName();
1010 $contactTable = CRM_Contact_BAO_Contact::getTableName();
1011 $deliveredTable = CRM_Mailing_Event_BAO_Delivered::getTableName();
1012 $bounceTable = CRM_Mailing_Event_BAO_Bounce::getTableName();
1013
1014 $query = " SELECT $queueTable.id,
1015 $emailTable.email as email,
1016 $queueTable.contact_id,
1017 $queueTable.hash,
1018 NULL as phone
1019 FROM $queueTable
1020 INNER JOIN $emailTable
1021 ON $queueTable.email_id = $emailTable.id
1022 INNER JOIN $contactTable
1023 ON $contactTable.id = $emailTable.contact_id
1024 LEFT JOIN $deliveredTable
1025 ON $queueTable.id = $deliveredTable.event_queue_id
1026 LEFT JOIN $bounceTable
1027 ON $queueTable.id = $bounceTable.event_queue_id
1028 WHERE $queueTable.job_id = " . $jobId . "
1029 AND $deliveredTable.id IS null
1030 AND $bounceTable.id IS null
1031 AND $contactTable.is_opt_out = 0";
1032
1033 if ($medium === 'sms') {
1034 $query = "
1035 SELECT $queueTable.id,
1036 $phoneTable.phone as phone,
1037 $queueTable.contact_id,
1038 $queueTable.hash,
1039 NULL as email
1040 FROM $queueTable
1041 INNER JOIN $phoneTable
1042 ON $queueTable.phone_id = $phoneTable.id
1043 INNER JOIN $contactTable
1044 ON $contactTable.id = $phoneTable.contact_id
1045 LEFT JOIN $deliveredTable
1046 ON $queueTable.id = $deliveredTable.event_queue_id
1047 LEFT JOIN $bounceTable
1048 ON $queueTable.id = $bounceTable.event_queue_id
1049 WHERE $queueTable.job_id = " . $jobId . "
1050 AND $deliveredTable.id IS null
1051 AND $bounceTable.id IS null
1052 AND ( $contactTable.is_opt_out = 0
1053 OR $contactTable.do_not_sms = 0 )";
1054 }
1055 $eq->query($query);
1056 return $eq;
1057 }
1058
1059 }