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