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