Merge pull request #13230 from colemanw/Api3
[civicrm-core.git] / CRM / Mailing / BAO / MailingJob.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
8c9251b3 6 | Copyright CiviCRM LLC (c) 2004-2018 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
8c9251b3 31 * @copyright CiviCRM LLC (c) 2004-2018
6a488035
TO
32 */
33
34require_once 'Mail.php';
4c6ce474
EM
35
36/**
37 * Class CRM_Mailing_BAO_MailingJob
38 */
9da8dc8c 39class CRM_Mailing_BAO_MailingJob extends CRM_Mailing_DAO_MailingJob {
7da04cde 40 const MAX_CONTACTS_TO_PROCESS = 1000;
6a488035 41
97b7d4a0 42 /**
a335f6b2 43 * (Dear God Why) Keep a global count of mails processed within the current
97b7d4a0
TO
44 * request.
45 *
97b7d4a0
TO
46 * @var int
47 */
48 static $mailsProcessed = 0;
49
6a488035 50 /**
fe482240 51 * Class constructor.
6a488035 52 */
00be9182 53 public function __construct() {
6a488035
TO
54 parent::__construct();
55 }
56
af4c09bc 57 /**
dbb0d30b 58 * Create mailing job.
59 *
c490a46a 60 * @param array $params
af4c09bc 61 *
dbb0d30b 62 * @return \CRM_Mailing_BAO_MailingJob
63 * @throws \CRM_Core_Exception
af4c09bc 64 */
84dd5db6 65 static public function create($params) {
f487e358 66 if (empty($params['id']) && empty($params['mailing_id'])) {
85d20752
TO
67 throw new CRM_Core_Exception("Failed to create job: Unknown mailing ID");
68 }
f487e358 69 $op = empty($params['id']) ? 'create' : 'edit';
70 CRM_Utils_Hook::pre($op, 'MailingJob', CRM_Utils_Array::value('id', $params), $params);
71
72 $jobDAO = new CRM_Mailing_BAO_MailingJob();
73 $jobDAO->copyValues($params, TRUE);
74 $jobDAO->save();
75 if (!empty($params['mailing_id'])) {
76 CRM_Mailing_BAO_Mailing::getRecipients($params['mailing_id']);
77 }
78 CRM_Utils_Hook::post($op, 'MailingJob', $jobDAO->id, $jobDAO);
79 return $jobDAO;
6a488035 80 }
af4c09bc 81
6a488035 82 /**
dbb0d30b 83 * Initiate all pending/ready jobs.
6a488035 84 *
100fef9d 85 * @param array $testParams
dbb0d30b 86 * @param string $mode
87 *
88 * @return bool|null
6a488035
TO
89 */
90 public static function runJobs($testParams = NULL, $mode = NULL) {
9da8dc8c 91 $job = new CRM_Mailing_BAO_MailingJob();
6a488035 92
353ffa53 93 $jobTable = CRM_Mailing_DAO_MailingJob::getTableName();
6a488035 94 $mailingTable = CRM_Mailing_DAO_Mailing::getTableName();
57873f1b 95 $mailerBatchLimit = Civi::settings()->get('mailerBatchLimit');
6a488035
TO
96
97 if (!empty($testParams)) {
98 $query = "
99 SELECT *
100 FROM $jobTable
101 WHERE id = {$testParams['job_id']}";
102 $job->query($query);
103 }
104 else {
105 $currentTime = date('YmdHis');
353ffa53
TO
106 $mailingACL = CRM_Mailing_BAO_Mailing::mailingACL('m');
107 $domainID = CRM_Core_Config::domainID();
6a488035
TO
108
109 $modeClause = 'AND m.sms_provider_id IS NULL';
110 if ($mode == 'sms') {
111 $modeClause = 'AND m.sms_provider_id IS NOT NULL';
112 }
113
114 // Select the first child job that is scheduled
115 // CRM-6835
116 $query = "
117 SELECT j.*
118 FROM $jobTable j,
119 $mailingTable m
120 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
121 {$modeClause}
122 AND j.is_test = 0
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')
129 AND {$mailingACL}
ce5f98aa 130 ORDER BY j.scheduled_date ASC,
daacf196 131 j.id
6a488035
TO
132 ";
133
134 $job->query($query);
135 }
136
6a488035
TO
137 while ($job->fetch()) {
138 // still use job level lock for each child job
83617886 139 $lock = Civi::lockManager()->acquire("data.mailing.job.{$job->id}");
6a488035
TO
140 if (!$lock->isAcquired()) {
141 continue;
142 }
143
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
1a5727bd 149 $job->status = CRM_Core_DAO::getFieldValue(
cbe30f5a 150 'CRM_Mailing_DAO_MailingJob',
6a488035 151 $job->id,
6606b2e1
DL
152 'status',
153 'id',
154 TRUE
6a488035
TO
155 );
156
1a5727bd
DL
157 if (
158 $job->status != 'Running' &&
6a488035
TO
159 $job->status != 'Scheduled'
160 ) {
161 // this includes Cancelled and other statuses, CRM-4246
162 $lock->release();
163 continue;
164 }
165 }
166
167 /* Queue up recipients for the child job being launched */
168
169 if ($job->status != 'Running') {
170 $transaction = new CRM_Core_Transaction();
171
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);
175
f487e358 176 // Update to show job has started.
177 self::create([
178 'id' => $job->id,
179 'start_date' => date('YmdHis'),
180 'status' => 'Running',
181 ]);
6a488035
TO
182
183 $transaction->commit();
184 }
185
186 // Get the mailer
6a488035 187 if ($mode === NULL) {
048222df 188 $mailer = \Civi::service('pear_mail');
6a488035
TO
189 }
190 elseif ($mode == 'sms') {
191 $mailer = CRM_SMS_Provider::singleton(array('mailing_id' => $job->mailing_id));
192 }
193
194 // Compose and deliver each child job
aa4343bc
TO
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));
197 }
198 else {
199 $isComplete = $job->deliver($mailer, $testParams);
200 }
6a488035
TO
201
202 CRM_Utils_Hook::post('create', 'CRM_Mailing_DAO_Spool', $job->id, $isComplete);
203
204 // Mark the child complete
205 if ($isComplete) {
25606795 206 // Finish the job.
6a488035
TO
207
208 $transaction = new CRM_Core_Transaction();
f487e358 209 self::create(['id' => $job->id, 'end_date' => date('YmdHis'), 'status' => 'Complete']);
6a488035
TO
210 $transaction->commit();
211
212 // don't mark the mailing as complete
213 }
214
215 // Release the child joblock
216 $lock->release();
217
218 if ($testParams) {
219 return $isComplete;
220 }
57873f1b
J
221
222 // CRM-17629: Stop processing jobs if mailer batch limit reached
223 if ($mailerBatchLimit > 0 && self::$mailsProcessed >= $mailerBatchLimit) {
224 break;
225 }
226
6a488035
TO
227 }
228 }
229
e0ef6999 230 /**
25606795
SB
231 * Post process to determine if the parent job
232 * as well as the mailing is complete after the run.
e0ef6999
EM
233 * @param null $mode
234 */
6a488035
TO
235 public static function runJobs_post($mode = NULL) {
236
9da8dc8c 237 $job = new CRM_Mailing_BAO_MailingJob();
6a488035
TO
238
239 $mailing = new CRM_Mailing_BAO_Mailing();
240
353ffa53
TO
241 $config = CRM_Core_Config::singleton();
242 $jobTable = CRM_Mailing_DAO_MailingJob::getTableName();
6a488035
TO
243 $mailingTable = CRM_Mailing_DAO_Mailing::getTableName();
244
245 $currentTime = date('YmdHis');
353ffa53
TO
246 $mailingACL = CRM_Mailing_BAO_Mailing::mailingACL('m');
247 $domainID = CRM_Core_Config::domainID();
6a488035
TO
248
249 $query = "
250 SELECT j.*
251 FROM $jobTable j,
252 $mailingTable m
253 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
254 AND j.is_test = 0
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,
260 j.start_date";
261
262 $job->query($query);
263
264 // For each parent job that is running, let's look at their child jobs
265 while ($job->fetch()) {
266
9da8dc8c 267 $child_job = new CRM_Mailing_BAO_MailingJob();
6a488035
TO
268
269 $child_job_sql = "
270 SELECT count(j.id)
271 FROM civicrm_mailing_job j, civicrm_mailing m
272 WHERE m.id = j.mailing_id
273 AND j.job_type = 'child'
274 AND j.parent_id = %1
275 AND j.status <> 'Complete'";
276 $params = array(1 => array($job->id, 'Integer'));
277
278 $anyChildLeft = CRM_Core_DAO::singleValueQuery($child_job_sql, $params);
279
280 // all of the child jobs are complete, update
281 // the parent job as well as the mailing status
282 if (!$anyChildLeft) {
283
284 $transaction = new CRM_Core_Transaction();
285
353ffa53
TO
286 $saveJob = new CRM_Mailing_DAO_MailingJob();
287 $saveJob->id = $job->id;
6a488035 288 $saveJob->end_date = date('YmdHis');
353ffa53 289 $saveJob->status = 'Complete';
6a488035
TO
290 $saveJob->save();
291
292 $mailing->reset();
293 $mailing->id = $job->mailing_id;
294 $mailing->is_completed = TRUE;
295 $mailing->save();
296 $transaction->commit();
b0fd9a5b
BS
297
298 // CRM-17763
c9a3cf8c 299 CRM_Utils_Hook::postMailing($job->mailing_id);
6a488035
TO
300 }
301 }
302 }
303
304
e0ef6999 305 /**
4f1f1f2a 306 * before we run jobs, we need to split the jobs
e0ef6999
EM
307 * @param int $offset
308 * @param null $mode
309 */
6a488035 310 public static function runJobs_pre($offset = 200, $mode = NULL) {
9da8dc8c 311 $job = new CRM_Mailing_BAO_MailingJob();
6a488035 312
353ffa53 313 $jobTable = CRM_Mailing_DAO_MailingJob::getTableName();
6a488035
TO
314 $mailingTable = CRM_Mailing_DAO_Mailing::getTableName();
315
316 $currentTime = date('YmdHis');
317 $mailingACL = CRM_Mailing_BAO_Mailing::mailingACL('m');
318
9da8dc8c 319 $workflowClause = CRM_Mailing_BAO_MailingJob::workflowClause();
6a488035
TO
320
321 $domainID = CRM_Core_Config::domainID();
322
323 $modeClause = 'AND m.sms_provider_id IS NULL';
324 if ($mode == 'sms') {
325 $modeClause = 'AND m.sms_provider_id IS NOT NULL';
326 }
327
328 // Select all the mailing jobs that are created from
329 // when the mailing is submitted or scheduled.
330 $query = "
331 SELECT j.*
332 FROM $jobTable j,
333 $mailingTable m
334 WHERE m.id = j.mailing_id AND m.domain_id = {$domainID}
335 $workflowClause
336 $modeClause
337 AND j.is_test = 0
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,
344 j.start_date";
345
6a488035
TO
346 $job->query($query);
347
6a488035
TO
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
83617886 352 $lock = Civi::lockManager()->acquire("data.mailing.job.{$job->id}");
6a488035
TO
353 if (!$lock->isAcquired()) {
354 continue;
355 }
356
357 // Re-fetch the job status in case things
358 // changed between the first query and now
359 // to avoid race conditions
6606b2e1 360 $job->status = CRM_Core_DAO::getFieldValue(
cbe30f5a 361 'CRM_Mailing_DAO_MailingJob',
6a488035 362 $job->id,
6606b2e1
DL
363 'status',
364 'id',
365 TRUE
6a488035
TO
366 );
367 if ($job->status != 'Scheduled') {
368 $lock->release();
369 continue;
370 }
371
2cf4876c
SL
372 $transaction = new CRM_Core_Transaction();
373
6a488035
TO
374 $job->split_job($offset);
375
f487e358 376 // Update the status of the parent job
377 self::create(['id' => $job->id, 'start_date' => date('YmdHis'), 'status' => 'Running']);
6a488035
TO
378 $transaction->commit();
379
380 // Release the job lock
381 $lock->release();
382 }
383 }
384
e0ef6999 385 /**
fe482240 386 * Split the parent job into n number of child job based on an offset.
4f1f1f2a 387 * If null or 0 , we create only one child job
e0ef6999
EM
388 * @param int $offset
389 */
6a488035
TO
390 public function split_job($offset = 200) {
391 $recipient_count = CRM_Mailing_BAO_Recipients::mailingSize($this->mailing_id);
392
9da8dc8c 393 $jobTable = CRM_Mailing_DAO_MailingJob::getTableName();
6a488035 394
6a488035
TO
395 $dao = new CRM_Core_DAO();
396
397 $sql = "
398INSERT INTO civicrm_mailing_job
399(`mailing_id`, `scheduled_date`, `status`, `job_type`, `parent_id`, `job_offset`, `job_limit`)
400VALUES (%1, %2, %3, %4, %5, %6, %7)
401";
35f7561f 402 $params = array(
353ffa53 403 1 => array($this->mailing_id, 'Integer'),
6a488035
TO
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'),
410 );
411
412 // create one child job if the mailing size is less than the offset
cbe30f5a 413 // probably use a CRM_Mailing_DAO_MailingJob( );
6a488035
TO
414 if (empty($offset) ||
415 $recipient_count <= $offset
416 ) {
417 CRM_Core_DAO::executeQuery($sql, $params);
418 }
419 else {
420 // Creating 'child jobs'
198c9339
RT
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);
6a488035
TO
424 $params[6][0] = $i;
425 $params[7][0] = $offset;
426 CRM_Core_DAO::executeQuery($sql, $params);
427 }
428 }
2cf4876c 429
6a488035
TO
430 }
431
e0ef6999 432 /**
100fef9d 433 * @param array $testParams
e0ef6999 434 */
6a488035
TO
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);
440 }
441 else {
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);
445
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
353ffa53 449 $now = time();
6a488035 450 $params = array();
353ffa53 451 $count = 0;
6a488035 452 while ($recipients->fetch()) {
81f62fdb 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)) {
456 continue;
457 }
458
6a488035
TO
459 if ($recipients->phone_id) {
460 $recipients->email_id = "null";
461 }
462 else {
463 $recipients->phone_id = "null";
464 }
465
466 $params[] = array(
467 $this->id,
468 $recipients->email_id,
469 $recipients->contact_id,
470 $recipients->phone_id,
471 );
472 $count++;
dfb542fc 473 if ($count % CRM_Mailing_Config::BULK_MAIL_INSERT_COUNT == 0) {
6a488035
TO
474 CRM_Mailing_Event_BAO_Queue::bulkCreate($params, $now);
475 $count = 0;
476 $params = array();
477 }
478 }
479
480 if (!empty($params)) {
481 CRM_Mailing_Event_BAO_Queue::bulkCreate($params, $now);
482 }
483 }
484 }
485
486 /**
fe482240 487 * Send the mailing.
6a488035 488 *
7705c640
TO
489 * @deprecated
490 * This is used by CiviMail but will be made redundant by FlexMailer.
90c8230e
TO
491 * @param object $mailer
492 * A Mail object to send the messages.
2a6da8d7 493 *
100fef9d 494 * @param array $testParams
7705c640 495 * @return bool
6a488035
TO
496 */
497 public function deliver(&$mailer, $testParams = NULL) {
aa4343bc
TO
498 if (\Civi::settings()->get('experimentalFlexMailerEngine')) {
499 throw new \RuntimeException("Cannot use legacy deliver() when experimentalFlexMailerEngine is enabled");
500 }
501
6a488035
TO
502 $mailing = new CRM_Mailing_BAO_Mailing();
503 $mailing->id = $this->mailing_id;
504 $mailing->find(TRUE);
505 $mailing->free();
506
97b7d4a0 507 $config = NULL;
6a488035
TO
508
509 if ($config == NULL) {
510 $config = CRM_Core_Config::singleton();
511 }
512
a7c57397
TO
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);
fd1f3a26
SV
515 }
516
6a488035
TO
517 $job_date = CRM_Utils_Date::isoToMysql($this->scheduled_date);
518 $fields = array();
519
520 if (!empty($testParams)) {
a5db8e6f 521 $mailing->subject = ts('[CiviMail Draft]') . ' ' . $mailing->subject;
6a488035
TO
522 }
523
524 CRM_Mailing_BAO_Mailing::tokenReplace($mailing);
525
526 // get and format attachments
527 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_mailing', $mailing->id);
528
529 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
530 CRM_Core_Smarty::registerStringResource();
531 }
532
df7f4ae1
DL
533 // CRM-12376
534 // This handles the edge case scenario where all the mails
25606795 535 // have been delivered in prior jobs.
df7f4ae1 536 $isDelivered = TRUE;
6a488035 537
dc00ac6d
TO
538 // make sure that there's no more than $mailerBatchLimit mails processed in a run
539 $mailerBatchLimit = Civi::settings()->get('mailerBatchLimit');
453c7bb8 540 $eq = self::findPendingTasks($this->id, $mailing->sms_provider_id ? 'sms' : 'email');
6a488035 541 while ($eq->fetch()) {
dc00ac6d 542 if ($mailerBatchLimit > 0 && self::$mailsProcessed >= $mailerBatchLimit) {
6a488035
TO
543 if (!empty($fields)) {
544 $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
545 }
546 $eq->free();
547 return FALSE;
548 }
97b7d4a0 549 self::$mailsProcessed++;
6a488035
TO
550
551 $fields[] = array(
552 'id' => $eq->id,
553 'hash' => $eq->hash,
554 'contact_id' => $eq->contact_id,
555 'email' => $eq->email,
556 'phone' => $eq->phone,
557 );
558 if (count($fields) == self::MAX_CONTACTS_TO_PROCESS) {
559 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
560 if (!$isDelivered) {
561 $eq->free();
562 return $isDelivered;
563 }
564 $fields = array();
565 }
566 }
567
568 $eq->free();
569
570 if (!empty($fields)) {
571 $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
572 }
573 return $isDelivered;
574 }
575
e0ef6999 576 /**
7705c640
TO
577 * @deprecated
578 * This is used by CiviMail but will be made redundant by FlexMailer.
519947b8
TO
579 * @param array $fields
580 * List of intended recipients.
581 * Each recipient is an array with keys 'hash', 'contact_id', 'email', etc.
e0ef6999
EM
582 * @param $mailing
583 * @param $mailer
584 * @param $job_date
585 * @param $attachments
586 *
587 * @return bool|null
588 * @throws Exception
589 */
6a488035
TO
590 public function deliverGroup(&$fields, &$mailing, &$mailer, &$job_date, &$attachments) {
591 static $smtpConnectionErrors = 0;
592
1a5727bd 593 if (!is_object($mailer) || empty($fields)) {
6a488035
TO
594 CRM_Core_Error::fatal();
595 }
596
597 // get the return properties
598 $returnProperties = $mailing->getReturnProperties();
353ffa53
TO
599 $params = $targetParams = $deliveredParams = array();
600 $count = 0;
e8654207 601 $retryGroup = FALSE;
7a9646c1 602
3d9b94a1
SB
603 // CRM-15702: Sending bulk sms to contacts without e-mail address fails.
604 // Solution is to skip checking for on hold
25606795 605 $skipOnHold = TRUE; //do include a statement to check wether e-mail address is on hold
e36508bf 606 if ($mailing->sms_provider_id) {
35f7561f 607 $skipOnHold = FALSE; //do not include a statement to check wether e-mail address is on hold
e36508bf 608 }
6a488035
TO
609
610 foreach ($fields as $key => $field) {
611 $params[] = $field['contact_id'];
612 }
613
614 $details = CRM_Utils_Token::getTokenDetails(
615 $params,
616 $returnProperties,
e36508bf 617 $skipOnHold, TRUE, NULL,
6a488035
TO
618 $mailing->getFlattenedTokens(),
619 get_class($this),
620 $this->id
621 );
622
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();
628 }
6a488035 629
25606795 630 // Compose the mailing.
6a488035
TO
631 $recipient = $replyToEmail = NULL;
632 $replyValue = strcmp($mailing->replyto_email, $mailing->from_email);
633 if ($replyValue) {
634 $replyToEmail = $mailing->replyto_email;
635 }
636
7eebf0c7 637 $message = $mailing->compose(
1a5727bd 638 $this->id, $field['id'], $field['hash'],
6a488035
TO
639 $field['contact_id'], $field['email'],
640 $recipient, FALSE, $details[0][$contactID], $attachments,
641 FALSE, NULL, $replyToEmail
642 );
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
647 continue;
648 }
649
25606795 650 // Send the mailing.
6a488035 651
ca807bbe
SL
652 $body = $message->get();
653 $headers = $message->headers();
6a488035
TO
654
655 if ($mailing->sms_provider_id) {
656 $provider = CRM_SMS_Provider::singleton(array('mailing_id' => $mailing->id));
353ffa53
TO
657 $body = $provider->getMessage($message, $field['contact_id'], $details[0][$contactID]);
658 $headers = $provider->getRecipientDetails($field, $details[0][$contactID]);
6a488035
TO
659 }
660
661 // make $recipient actually be the *encoded* header, so as not to baffle Mail_RFC822, CRM-5743
662 $recipient = $headers['To'];
663 $result = NULL;
664
665 // disable error reporting on real mailings (but leave error reporting for tests), CRM-5744
666 if ($job_date) {
6a4257d4 667 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
6a488035
TO
668 }
669
670 $result = $mailer->send($recipient, $headers, $body, $this->id);
671
672 if ($job_date) {
6a4257d4 673 unset($errorScope);
6a488035
TO
674 }
675
c5a6413b 676 if (is_a($result, 'PEAR_Error') && !$mailing->sms_provider_id) {
6a488035
TO
677 // CRM-9191
678 $message = $result->getMessage();
206dc844 679 if ($this->isTemporaryError($message)) {
6a488035
TO
680 // lets log this message and code
681 $code = $result->getCode();
18810158 682 CRM_Core_Error::debug_log_message("SMTP Socket Error or failed to set sender error. Message: $message, Code: $code");
6a488035
TO
683
684 // these are socket write errors which most likely means smtp connection errors
e8654207 685 // lets skip them and reconnect.
6a488035
TO
686 $smtpConnectionErrors++;
687 if ($smtpConnectionErrors <= 5) {
e8654207 688 $mailer->disconnect();
689 $retryGroup = TRUE;
6a488035
TO
690 continue;
691 }
692
6a488035
TO
693 // seems like we have too many of them in a row, we should
694 // write stuff to disk and abort the cron job
2ede60ec
DL
695 $this->writeToDB(
696 $deliveredParams,
6a488035
TO
697 $targetParams,
698 $mailing,
699 $job_date
700 );
701
702 CRM_Core_Error::debug_log_message("Too many SMTP Socket Errors. Exiting");
703 CRM_Utils_System::civiExit();
704 }
705
25606795 706 // Register the bounce event.
6a488035
TO
707
708 $params = array(
709 'event_queue_id' => $field['id'],
710 'job_id' => $this->id,
711 'hash' => $field['hash'],
712 );
713 $params = array_merge($params,
714 CRM_Mailing_BAO_BouncePattern::match($result->getMessage())
715 );
716 CRM_Mailing_Event_BAO_Bounce::create($params);
717 }
39373d13
JM
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());
724 }
6a488035 725 else {
25606795 726 // Register the delivery event.
6a488035
TO
727 $deliveredParams[] = $field['id'];
728 $targetParams[] = $field['contact_id'];
729
730 $count++;
dfb542fc 731 if ($count % CRM_Mailing_Config::BULK_MAIL_INSERT_COUNT == 0) {
2ede60ec
DL
732 $this->writeToDB(
733 $deliveredParams,
6a488035
TO
734 $targetParams,
735 $mailing,
736 $job_date
737 );
738 $count = 0;
739
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
1a5727bd 743 $status = CRM_Core_DAO::getFieldValue(
cbe30f5a 744 'CRM_Mailing_DAO_MailingJob',
6a488035 745 $this->id,
1a5727bd
DL
746 'status',
747 'id',
748 TRUE
6a488035 749 );
1a5727bd 750
6a488035
TO
751 if ($status != 'Running') {
752 return FALSE;
753 }
754 }
755 }
756
757 unset($result);
758
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--;
763 }
764
765 // If we have enabled the Throttle option, this is the time to enforce it.
dc00ac6d
TO
766 $mailThrottleTime = Civi::settings()->get('mailThrottleTime');
767 if (!empty($mailThrottleTime)) {
768 usleep((int ) $mailThrottleTime);
6a488035
TO
769 }
770 }
771
2ede60ec
DL
772 $result = $this->writeToDB(
773 $deliveredParams,
6a488035
TO
774 $targetParams,
775 $mailing,
776 $job_date
777 );
778
e8654207 779 if ($retryGroup) {
780 return FALSE;
781 }
782
6a488035
TO
783 return $result;
784 }
785
206dc844 786 /**
787 * Determine if an SMTP error is temporary or permanent.
788 *
789 * @param string $message
790 * PEAR error message.
791 * @return bool
792 * TRUE - Temporary/retriable error
793 * FALSE - Permanent/non-retriable error
794 */
795 protected function isTemporaryError($message) {
796 // SMTP response code is buried in the message.
797 $code = preg_match('/ \(code: (.+), response: /', $message, $matches) ? $matches[1] : '';
798
799 if (strpos($message, 'Failed to write to socket') !== FALSE) {
800 return TRUE;
801 }
802
803 // Register 5xx SMTP response code (permanent failure) as bounce.
f1134501 804 if (isset($code{0}) && $code{0} === '5') {
206dc844 805 return FALSE;
806 }
807
808 if (strpos($message, 'Failed to set sender') !== FALSE) {
809 return TRUE;
810 }
811
812 if (strpos($message, 'Failed to add recipient') !== FALSE) {
813 return TRUE;
814 }
815
816 if (strpos($message, 'Failed to send data') !== FALSE) {
817 return TRUE;
818 }
819
820 return FALSE;
821 }
822
6a488035 823 /**
fe482240 824 * Cancel a mailing.
6a488035 825 *
90c8230e
TO
826 * @param int $mailingId
827 * The id of the mailing to be canceled.
6a488035
TO
828 */
829 public static function cancel($mailingId) {
830 $sql = "
831SELECT *
832FROM civicrm_mailing_job
833WHERE mailing_id = %1
834AND is_test = 0
835AND ( ( job_type IS NULL ) OR
836 job_type <> 'child' )
837";
838 $params = array(1 => array($mailingId, 'Integer'));
839 $job = CRM_Core_DAO::executeQuery($sql, $params);
840 if ($job->fetch() &&
841 in_array($job->status, array('Scheduled', 'Running', 'Paused'))
842 ) {
843
f487e358 844 self::create(['id' => $job->id, 'end_date' => date('YmdHis'), 'status' => 'Canceled']);
6a488035
TO
845
846 // also cancel all child jobs
847 $sql = "
848UPDATE civicrm_mailing_job
849SET status = 'Canceled',
850 end_date = %2
851WHERE parent_id = %1
852AND is_test = 0
853AND job_type = 'child'
854AND status IN ( 'Scheduled', 'Running', 'Paused' )
855";
35f7561f 856 $params = array(
353ffa53 857 1 => array($job->id, 'Integer'),
6a488035
TO
858 2 => array(date('YmdHis'), 'Timestamp'),
859 );
860 CRM_Core_DAO::executeQuery($sql, $params);
6a488035
TO
861 }
862 }
863
4aa8f804
JP
864 /**
865 * Pause a mailing
67d4ed51
JP
866 *
867 * @param int $mailingID
868 * The id of the mailing to be paused.
4aa8f804
JP
869 */
870 public static function pause($mailingID) {
871 $sql = "
872 UPDATE civicrm_mailing_job
873 SET status = 'Paused'
874 WHERE mailing_id = %1
875 AND is_test = 0
876 AND status IN ('Scheduled', 'Running')
877 ";
878 CRM_Core_DAO::executeQuery($sql, array(1 => array($mailingID, 'Integer')));
4aa8f804
JP
879 }
880
881 /**
882 * Resume a mailing
67d4ed51
JP
883 *
884 * @param int $mailingID
885 * The id of the mailing to be resumed.
4aa8f804
JP
886 */
887 public static function resume($mailingID) {
888 $sql = "
889 UPDATE civicrm_mailing_job
890 SET status = 'Scheduled'
891 WHERE mailing_id = %1
892 AND is_test = 0
893 AND start_date IS NULL
894 AND status = 'Paused'
895 ";
896 CRM_Core_DAO::executeQuery($sql, array(1 => array($mailingID, 'Integer')));
897
898 $sql = "
899 UPDATE civicrm_mailing_job
900 SET status = 'Running'
901 WHERE mailing_id = %1
902 AND is_test = 0
903 AND start_date IS NOT NULL
904 AND status = 'Paused'
905 ";
906 CRM_Core_DAO::executeQuery($sql, array(1 => array($mailingID, 'Integer')));
4aa8f804
JP
907 }
908
6a488035 909 /**
fe482240 910 * Return a translated status enum string.
6a488035 911 *
90c8230e
TO
912 * @param string $status
913 * The status enum.
6a488035 914 *
a6c01b45
CW
915 * @return string
916 * The translated version
6a488035
TO
917 */
918 public static function status($status) {
919 static $translation = NULL;
920
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'),
928 );
929 }
930 return CRM_Utils_Array::value($status, $translation, ts('Not scheduled'));
931 }
932
933 /**
934 * Return a workflow clause for use in SQL queries,
935 * to only process jobs that are approved.
936 *
a6c01b45
CW
937 * @return string
938 * For use in a WHERE clause
6a488035
TO
939 */
940 public static function workflowClause() {
941 // add an additional check and only process
942 // jobs that are approved
943 if (CRM_Mailing_Info::workflowEnabled()) {
676159c9 944 $approveOptionID = CRM_Core_PseudoConstant::getKey('CRM_Mailing_BAO_Mailing', 'approval_status_id', 'Approved');
6a488035
TO
945 if ($approveOptionID) {
946 return " AND m.approval_status_id = $approveOptionID ";
947 }
948 }
949 return '';
950 }
951
e0ef6999 952 /**
100fef9d
CW
953 * @param array $deliveredParams
954 * @param array $targetParams
e0ef6999
EM
955 * @param $mailing
956 * @param $job_date
957 *
958 * @return bool
959 * @throws CRM_Core_Exception
960 * @throws Exception
961 */
2ede60ec
DL
962 public function writeToDB(
963 &$deliveredParams,
6a488035
TO
964 &$targetParams,
965 &$mailing,
966 $job_date
967 ) {
968 static $activityTypeID = NULL;
2ede60ec 969 static $writeActivity = NULL;
6a488035
TO
970
971 if (!empty($deliveredParams)) {
972 CRM_Mailing_Event_BAO_Delivered::bulkCreate($deliveredParams);
973 $deliveredParams = array();
974 }
975
2ede60ec 976 if ($writeActivity === NULL) {
aaffa79f 977 $writeActivity = Civi::settings()->get('write_activity_record');
2ede60ec 978 }
6a488035 979
2ede60ec
DL
980 if (!$writeActivity) {
981 return TRUE;
982 }
983
984 $result = TRUE;
985 if (!empty($targetParams) && !empty($mailing->scheduled_id)) {
6a488035 986 if (!$activityTypeID) {
6a488035
TO
987 if ($mailing->sms_provider_id) {
988 $mailing->subject = $mailing->name;
a7321423 989 $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Mass SMS'
6a488035
TO
990 );
991 }
2ede60ec 992 else {
a7321423 993 $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Bulk Email');
2ede60ec 994 }
6a488035
TO
995 if (!$activityTypeID) {
996 CRM_Core_Error::fatal();
997 }
998 }
999
6a488035
TO
1000 $activity = array(
1001 'source_contact_id' => $mailing->scheduled_id,
1002 // CRM-9519
1003 'target_contact_id' => array_unique($targetParams),
6a488035
TO
1004 'activity_type_id' => $activityTypeID,
1005 'source_record_id' => $this->mailing_id,
1006 'activity_date_time' => $job_date,
1007 'subject' => $mailing->subject,
1008 'status_id' => 2,
1009 'deleteActivityTarget' => FALSE,
1010 'campaign_id' => $mailing->campaign_id,
1011 );
1012
1013 //check whether activity is already created for this mailing.
1014 //if yes then create only target contact record.
1015 $query = "
1016SELECT id
1017FROM civicrm_activity
1018WHERE civicrm_activity.activity_type_id = %1
2ede60ec
DL
1019AND civicrm_activity.source_record_id = %2
1020";
6a488035 1021
2ede60ec
DL
1022 $queryParams = array(
1023 1 => array($activityTypeID, 'Integer'),
6a488035
TO
1024 2 => array($this->mailing_id, 'Integer'),
1025 );
2ede60ec 1026 $activityID = CRM_Core_DAO::singleValueQuery($query, $queryParams);
6a488035
TO
1027
1028 if ($activityID) {
1029 $activity['id'] = $activityID;
1030
1031 // CRM-9519
1032 if (CRM_Core_BAO_Email::isMultipleBulkMail()) {
b561230a
DL
1033 static $targetRecordID = NULL;
1034 if (!$targetRecordID) {
44f817d4 1035 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
b561230a
DL
1036 $targetRecordID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1037 }
1038
6a488035
TO
1039 // make sure we don't attempt to duplicate the target activity
1040 foreach ($activity['target_contact_id'] as $key => $targetID) {
b561230a
DL
1041 $sql = "
1042SELECT id
1043FROM civicrm_activity_contact
1044WHERE activity_id = $activityID
1045AND contact_id = $targetID
1046AND record_type_id = $targetRecordID
1047";
6a488035
TO
1048 if (CRM_Core_DAO::singleValueQuery($sql)) {
1049 unset($activity['target_contact_id'][$key]);
1050 }
1051 }
1052 }
1053 }
1054
2ede60ec 1055 if (is_a(CRM_Activity_BAO_Activity::create($activity), 'CRM_Core_Error')) {
6a488035
TO
1056 $result = FALSE;
1057 }
1058
1059 $targetParams = array();
1060 }
1061
1062 return $result;
1063 }
96025800 1064
453c7bb8 1065 /**
5f9481d6
TO
1066 * Search the mailing-event queue for a list of pending delivery tasks.
1067 *
453c7bb8
TO
1068 * @param int $jobId
1069 * @param string $medium
1070 * Ex: 'email' or 'sms'.
5f9481d6 1071 *
453c7bb8
TO
1072 * @return \CRM_Mailing_Event_BAO_Queue
1073 * A query object whose rows provide ('id', 'contact_id', 'hash') and ('email' or 'phone').
1074 */
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();
5f9481d6 1079 $phoneTable = CRM_Core_BAO_Phone::getTableName();
453c7bb8
TO
1080 $contactTable = CRM_Contact_BAO_Contact::getTableName();
1081 $deliveredTable = CRM_Mailing_Event_BAO_Delivered::getTableName();
1082 $bounceTable = CRM_Mailing_Event_BAO_Bounce::getTableName();
1083
1084 $query = " SELECT $queueTable.id,
1085 $emailTable.email as email,
1086 $queueTable.contact_id,
1087 $queueTable.hash,
1088 NULL as phone
1089 FROM $queueTable
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";
1102
1103 if ($medium === 'sms') {
1104 $query = "
1105 SELECT $queueTable.id,
1106 $phoneTable.phone as phone,
1107 $queueTable.contact_id,
1108 $queueTable.hash,
1109 NULL as email
1110 FROM $queueTable
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 )";
1124 }
1125 $eq->query($query);
1126 return $eq;
1127 }
1128
6f65a84f 1129 /**
1130 * Delete the mailing job.
1131 *
1132 * @param int $id
1133 * Mailing Job id.
1134 *
1135 * @return mixed
1136 */
1137 public static function del($id) {
1138 CRM_Utils_Hook::pre('delete', 'MailingJob', $id, CRM_Core_DAO::$_nullArray);
1139
1140 $jobDAO = new CRM_Mailing_BAO_MailingJob();
1141 $jobDAO->id = $id;
1142 $result = $jobDAO->delete();
1143
1144 CRM_Utils_Hook::post('delete', 'MailingJob', $jobDAO->id, $jobDAO);
1145
1146 return $result;
1147 }
1148
6a488035 1149}