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