CRM-17028: Yearly and Monthly Repeat Reminders send on every cron for 24 hours
[civicrm-core.git] / CRM / Core / BAO / ActionSchedule.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
32 * $Id$
33 *
34 */
35
36 /**
37 * This class contains functions for managing Scheduled Reminders
38 */
39 class CRM_Core_BAO_ActionSchedule extends CRM_Core_DAO_ActionSchedule {
40
41 /**
42 * @param int $id
43 *
44 * @return array
45 */
46 public static function getMapping($id = NULL) {
47 static $_action_mapping;
48
49 if ($id && !is_null($_action_mapping) && isset($_action_mapping[$id])) {
50 return $_action_mapping[$id];
51 }
52
53 $dao = new CRM_Core_DAO_ActionMapping();
54 if ($id) {
55 $dao->id = $id;
56 }
57 $dao->find();
58
59 $mapping = array();
60 while ($dao->fetch()) {
61 $defaults = array();
62 CRM_Core_DAO::storeValues($dao, $defaults);
63 $mapping[$dao->id] = $defaults;
64 }
65 $_action_mapping = $mapping;
66
67 return $mapping;
68 }
69
70 /**
71 * Get all fields of the type Date.
72 */
73 public static function getDateFields() {
74 $allFields = CRM_Core_BAO_CustomField::getFields('');
75 $dateFields = array(
76 'birth_date' => ts('Birth Date'),
77 'created_date' => ts('Created Date'),
78 'modified_date' => ts('Modified Date'),
79 );
80 foreach ($allFields as $fieldID => $field) {
81 if ($field['data_type'] == 'Date') {
82 $dateFields["custom_$fieldID"] = $field['label'];
83 }
84 }
85 return $dateFields;
86 }
87
88 /**
89 * Retrieve list of selections/drop downs for Scheduled Reminder form
90 *
91 * @param bool $id
92 * Mapping id.
93 *
94 * @return array
95 * associated array of all the drop downs in the form
96 */
97 public static function getSelection($id = NULL) {
98 $mapping = self::getMapping();
99 $activityStatus = CRM_Core_PseudoConstant::activityStatus();
100 $activityType = CRM_Core_PseudoConstant::activityType(TRUE, TRUE);
101
102 $participantStatus = CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label');
103 $event = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
104 $eventType = CRM_Event_PseudoConstant::eventType();
105 $eventTemplate = CRM_Event_PseudoConstant::eventTemplates();
106 $autoRenew = CRM_Core_OptionGroup::values('auto_renew_options');
107 $membershipType = CRM_Member_PseudoConstant::membershipType();
108 $dateFieldParams = array('data_type' => 'Date');
109 $dateFields = self::getDateFields();
110 $contactOptions = CRM_Core_OptionGroup::values('contact_date_reminder_options');
111
112 asort($activityType);
113
114 $sel1 = $sel2 = $sel3 = $sel4 = $sel5 = array();
115 $options = array(
116 'manual' => ts('Choose Recipient(s)'),
117 'group' => ts('Select Group'),
118 );
119
120 $entityMapping = array();
121 $recipientMapping = array_combine(array_keys($options), array_keys($options));
122
123 if (!$id) {
124 $id = 1;
125 }
126
127 foreach ($mapping as $value) {
128 $entityValue = CRM_Utils_Array::value('entity_value', $value);
129 $entityStatus = CRM_Utils_Array::value('entity_status', $value);
130 $entityRecipient = CRM_Utils_Array::value('entity_recipient', $value);
131 $valueLabel = array('- ' . strtolower(CRM_Utils_Array::value('entity_value_label', $value)) . ' -');
132 $key = CRM_Utils_Array::value('id', $value);
133 $entityMapping[$key] = CRM_Utils_Array::value('entity', $value);
134
135 $sel1Val = NULL;
136 switch ($entityValue) {
137 case 'activity_type':
138 if ($value['entity'] == 'civicrm_activity') {
139 $sel1Val = ts('Activity');
140 }
141 $sel2[$key] = $valueLabel + $activityType;
142 break;
143
144 case 'event_type':
145 if ($value['entity'] == 'civicrm_participant') {
146 $sel1Val = ts('Event Type');
147 }
148 $sel2[$key] = $valueLabel + $eventType;
149 break;
150
151 case 'event_template':
152 if ($value['entity'] == 'civicrm_participant') {
153 $sel1Val = ts('Event Template');
154 }
155 $sel2[$key] = $valueLabel + $eventTemplate;
156 break;
157
158 case 'civicrm_event':
159 if ($value['entity'] == 'civicrm_participant') {
160 $sel1Val = ts('Event Name');
161 }
162 $sel2[$key] = $valueLabel + $event;
163 break;
164
165 case 'civicrm_membership_type':
166 if ($value['entity'] == 'civicrm_membership') {
167 $sel1Val = ts('Membership');
168 }
169 $sel2[$key] = $valueLabel + $membershipType;
170 break;
171
172 case 'civicrm_contact':
173 if ($value['entity'] == 'civicrm_contact') {
174 $sel1Val = ts('Contact');
175 }
176 $sel2[$key] = $dateFields;
177 break;
178 }
179 $sel1[$key] = $sel1Val;
180
181 if ($key == $id) {
182 if ($startDate = CRM_Utils_Array::value('entity_date_start', $value)) {
183 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
184 }
185 if ($endDate = CRM_Utils_Array::value('entity_date_end', $value)) {
186 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
187 }
188
189 switch ($entityRecipient) {
190 case 'activity_contacts':
191 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts');
192 $sel5[$entityRecipient] = $activityContacts + $options;
193 $recipientMapping += CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
194 break;
195
196 case 'event_contacts':
197 $eventContacts = CRM_Core_OptionGroup::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name');
198 $sel5[$entityRecipient] = $eventContacts + $options;
199 $recipientMapping += CRM_Core_OptionGroup::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
200 break;
201
202 case NULL:
203 $sel5[$entityRecipient] = $options;
204 break;
205 }
206 }
207 }
208 $sel3 = $sel2;
209
210 foreach ($mapping as $value) {
211 $entityStatus = CRM_Utils_Array::value('entity_status', $value);
212 $statusLabel = array('- ' . strtolower(CRM_Utils_Array::value('entity_status_label', $value)) . ' -');
213 $id = CRM_Utils_Array::value('id', $value);
214
215 switch ($entityStatus) {
216 case 'activity_status':
217 foreach ($sel3[$id] as $kkey => & $vval) {
218 $vval = $statusLabel + $activityStatus;
219 }
220 break;
221
222 case 'civicrm_participant_status_type':
223 foreach ($sel3[$id] as $kkey => & $vval) {
224 $vval = $statusLabel + $participantStatus;
225 }
226 break;
227
228 case 'auto_renew_options':
229 foreach ($sel3[$id] as $kkey => & $vval) {
230 $auto = 0;
231 if ($kkey) {
232 $auto = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $kkey, 'auto_renew');
233 }
234 if ($auto) {
235 $vval = $statusLabel + $autoRenew;
236 }
237 else {
238 $vval = $statusLabel;
239 }
240 }
241 break;
242
243 case 'contact_date_reminder_options':
244 foreach ($sel3[$id] as $kkey => & $vval) {
245 $vval = $contactOptions;
246 }
247 break;
248
249 case '':
250 $sel3[$id] = '';
251 break;
252
253 }
254 }
255 return array(
256 'sel1' => $sel1,
257 'sel2' => $sel2,
258 'sel3' => $sel3,
259 'sel4' => $sel4,
260 'sel5' => $sel5,
261 'entityMapping' => $entityMapping,
262 'recipientMapping' => $recipientMapping,
263 );
264 }
265
266 /**
267 * @param int $id
268 * @param int $isLimit
269 *
270 * @return array
271 */
272 public static function getSelection1($id = NULL, $isLimit = NULL) {
273 $mapping = self::getMapping($id);
274 $sel4 = $sel5 = array();
275 $options = array(
276 'manual' => ts('Choose Recipient(s)'),
277 'group' => ts('Select Group'),
278 );
279
280 $recipientMapping = array_combine(array_keys($options), array_keys($options));
281
282 foreach ($mapping as $value) {
283 $entityRecipient = CRM_Utils_Array::value('entity_recipient', $value);
284 $key = CRM_Utils_Array::value('id', $value);
285
286 if ($startDate = CRM_Utils_Array::value('entity_date_start', $value)) {
287 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
288 }
289 if ($endDate = CRM_Utils_Array::value('entity_date_end', $value)) {
290 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
291 }
292
293 switch ($entityRecipient) {
294 case 'activity_contacts':
295 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts');
296 $sel5[$id] = $activityContacts + $options;
297 $recipientMapping += CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
298 break;
299
300 case 'event_contacts':
301 //CRM-15536, don't provide participant_role option on choosing 'Also Include' for Event entity
302 if ($isLimit == 1) {
303 $options += CRM_Core_OptionGroup::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name');
304 }
305 $sel5[$id] = $options;
306 $recipientMapping += CRM_Core_OptionGroup::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
307 break;
308
309 case NULL:
310 $sel5[$id] = $options;
311 break;
312 }
313 }
314
315 return array(
316 'sel4' => $sel4,
317 'sel5' => $sel5[$id],
318 'recipientMapping' => $recipientMapping,
319 );
320 }
321
322 /**
323 * Retrieve list of Scheduled Reminders.
324 *
325 * @param bool $namesOnly
326 * Return simple list of names.
327 *
328 * @param null $entityValue
329 * @param int $id
330 *
331 * @return array
332 * (reference) reminder list
333 */
334 public static function &getList($namesOnly = FALSE, $entityValue = NULL, $id = NULL) {
335 $activity_type = CRM_Core_PseudoConstant::activityType(TRUE, TRUE);
336 $activity_status = CRM_Core_PseudoConstant::activityStatus();
337
338 $event_type = CRM_Event_PseudoConstant::eventType();
339 $civicrm_event = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
340 $civicrm_participant_status_type = CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label');
341 $event_template = CRM_Event_PseudoConstant::eventTemplates();
342 $civicrm_contact = self::getDateFields();
343
344 $auto_renew_options = CRM_Core_OptionGroup::values('auto_renew_options');
345 $contact_date_reminder_options = CRM_Core_OptionGroup::values('contact_date_reminder_options');
346 $civicrm_membership_type = CRM_Member_PseudoConstant::membershipType();
347
348 $entity = array(
349 'civicrm_activity' => 'Activity',
350 'civicrm_participant' => 'Event',
351 'civicrm_membership' => 'Member',
352 'civicrm_contact' => 'Contact',
353 );
354
355 $query = "
356 SELECT
357 title,
358 cam.entity,
359 cas.id as id,
360 cam.entity_value as entityValue,
361 cas.entity_value as entityValueIds,
362 cam.entity_status as entityStatus,
363 cas.entity_status as entityStatusIds,
364 cas.start_action_date as entityDate,
365 cas.start_action_offset,
366 cas.start_action_unit,
367 cas.start_action_condition,
368 cas.absolute_date,
369 is_repeat,
370 is_active
371
372 FROM civicrm_action_schedule cas
373 LEFT JOIN civicrm_action_mapping cam ON (cam.id = cas.mapping_id)
374 ";
375 $params = CRM_Core_DAO::$_nullArray;
376 $where = " WHERE 1 ";
377 if ($entityValue and $id) {
378 $where .= "
379 AND cas.entity_value = $id AND
380 cam.entity_value = '$entityValue'";
381
382 $params = array(
383 1 => array($id, 'Integer'),
384 2 => array($entityValue, 'String'),
385 );
386 }
387 $where .= " AND cas.used_for IS NULL";
388 $query .= $where;
389 $dao = CRM_Core_DAO::executeQuery($query);
390 while ($dao->fetch()) {
391 $list[$dao->id]['id'] = $dao->id;
392 $list[$dao->id]['title'] = $dao->title;
393 $list[$dao->id]['start_action_offset'] = $dao->start_action_offset;
394 $list[$dao->id]['start_action_unit'] = $dao->start_action_unit;
395 $list[$dao->id]['start_action_condition'] = $dao->start_action_condition;
396 $list[$dao->id]['entityDate'] = ucwords(str_replace('_', ' ', $dao->entityDate));
397 $list[$dao->id]['absolute_date'] = $dao->absolute_date;
398
399 $status = $dao->entityStatus;
400 $statusArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $dao->entityStatusIds);
401 foreach ($statusArray as & $s) {
402 $s = CRM_Utils_Array::value($s, $$status);
403 }
404 $statusIds = implode(', ', $statusArray);
405
406 $value = $dao->entityValue;
407 $valueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $dao->entityValueIds);
408 foreach ($valueArray as & $v) {
409 $v = CRM_Utils_Array::value($v, $$value);
410 }
411 $valueIds = implode(', ', $valueArray);
412 $list[$dao->id]['entity'] = $entity[$dao->entity];
413 $list[$dao->id]['value'] = $valueIds;
414 $list[$dao->id]['status'] = $statusIds;
415 $list[$dao->id]['is_repeat'] = $dao->is_repeat;
416 $list[$dao->id]['is_active'] = $dao->is_active;
417 }
418
419 return $list;
420 }
421
422 /**
423 * @param int $contactId
424 * @param $to
425 * @param int $scheduleID
426 * @param $from
427 * @param array $tokenParams
428 *
429 * @return bool|null
430 * @throws CRM_Core_Exception
431 */
432 public static function sendReminder($contactId, $to, $scheduleID, $from, $tokenParams) {
433 $email = $to['email'];
434 $phoneNumber = $to['phone'];
435 $schedule = new CRM_Core_DAO_ActionSchedule();
436 $schedule->id = $scheduleID;
437
438 $domain = CRM_Core_BAO_Domain::getDomain();
439 $result = NULL;
440 $hookTokens = array();
441
442 if ($schedule->find(TRUE)) {
443 $body_text = $schedule->body_text;
444 $body_html = $schedule->body_html;
445 $sms_body_text = $schedule->sms_body_text;
446 $body_subject = $schedule->subject;
447 if (!$body_text) {
448 $body_text = CRM_Utils_String::htmlToText($body_html);
449 }
450
451 $params = array(array('contact_id', '=', $contactId, 0, 0));
452 list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($params);
453
454 //CRM-4524
455 $contact = reset($contact);
456
457 if (!$contact || is_a($contact, 'CRM_Core_Error')) {
458 return NULL;
459 }
460
461 // merge activity tokens with contact array
462 $contact = array_merge($contact, $tokenParams);
463
464 //CRM-5734
465 CRM_Utils_Hook::tokenValues($contact, $contactId);
466
467 CRM_Utils_Hook::tokens($hookTokens);
468 $categories = array_keys($hookTokens);
469
470 $type = array('body_html' => 'html', 'body_text' => 'text', 'sms_body_text' => 'text');
471
472 foreach ($type as $bodyType => $value) {
473 $dummy_mail = new CRM_Mailing_BAO_Mailing();
474 if ($bodyType == 'sms_body_text') {
475 $dummy_mail->body_text = $$bodyType;
476 }
477 else {
478 $dummy_mail->$bodyType = $$bodyType;
479 }
480 $tokens = $dummy_mail->getTokens();
481
482 if ($$bodyType) {
483 CRM_Utils_Token::replaceGreetingTokens($$bodyType, NULL, $contact['contact_id']);
484 $$bodyType = CRM_Utils_Token::replaceDomainTokens($$bodyType, $domain, TRUE, $tokens[$value], TRUE);
485 $$bodyType = CRM_Utils_Token::replaceContactTokens($$bodyType, $contact, FALSE, $tokens[$value], FALSE, TRUE);
486 $$bodyType = CRM_Utils_Token::replaceComponentTokens($$bodyType, $contact, $tokens[$value], TRUE, FALSE);
487 $$bodyType = CRM_Utils_Token::replaceHookTokens($$bodyType, $contact, $categories, TRUE);
488 }
489 }
490 $html = $body_html;
491 $text = $body_text;
492 $sms_text = $sms_body_text;
493
494 $smarty = CRM_Core_Smarty::singleton();
495 foreach (array(
496 'text',
497 'html',
498 'sms_text',
499 ) as $elem) {
500 $$elem = $smarty->fetch("string:{$$elem}");
501 }
502
503 //@todo - this next section is a duplicate of function CRM_Utils_Token::getTokens
504 $matches = array();
505 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
506 $body_subject,
507 $matches,
508 PREG_PATTERN_ORDER
509 );
510
511 $subjectToken = NULL;
512 if ($matches[1]) {
513 foreach ($matches[1] as $token) {
514 list($type, $name) = preg_split('/\./', $token, 2);
515 if ($name) {
516 if (!isset($subjectToken[$type])) {
517 $subjectToken[$type] = array();
518 }
519 $subjectToken[$type][] = $name;
520 }
521 }
522 }
523
524 // @todo this (along with the copy-&-paste chunk above is a commonly repeated chunk of code & should be in a re-usable function
525 $messageSubject = CRM_Utils_Token::replaceContactTokens($body_subject, $contact, FALSE, $subjectToken);
526 $messageSubject = CRM_Utils_Token::replaceDomainTokens($messageSubject, $domain, TRUE, $subjectToken);
527 $messageSubject = CRM_Utils_Token::replaceComponentTokens($messageSubject, $contact, $subjectToken, TRUE);
528 $messageSubject = CRM_Utils_Token::replaceHookTokens($messageSubject, $contact, $categories, TRUE);
529
530 $messageSubject = $smarty->fetch("string:{$messageSubject}");
531
532 if ($schedule->mode == 'SMS' or $schedule->mode == 'User_Preference') {
533 $session = CRM_Core_Session::singleton();
534 $userID = $session->get('userID') ? $session->get('userID') : $contactId;
535 $smsParams = array(
536 'To' => $phoneNumber,
537 'provider_id' => $schedule->sms_provider_id,
538 'activity_subject' => $messageSubject,
539 );
540 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
541 'SMS',
542 'name'
543 );
544 $activityParams = array(
545 'source_contact_id' => $userID,
546 'activity_type_id' => $activityTypeID,
547 'activity_date_time' => date('YmdHis'),
548 'subject' => $messageSubject,
549 'details' => $sms_text,
550 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'),
551 );
552
553 $activity = CRM_Activity_BAO_Activity::create($activityParams);
554
555 CRM_Activity_BAO_Activity::sendSMSMessage($contactId,
556 $sms_text,
557 $smsParams,
558 $activity->id,
559 $userID
560 );
561 }
562
563 if ($schedule->mode == 'Email' or $schedule->mode == 'User_Preference') {
564 // set up the parameters for CRM_Utils_Mail::send
565 $mailParams = array(
566 'groupName' => 'Scheduled Reminder Sender',
567 'from' => $from,
568 'toName' => $contact['display_name'],
569 'toEmail' => $email,
570 'subject' => $messageSubject,
571 'entity' => 'action_schedule',
572 'entity_id' => $scheduleID,
573 );
574
575 if (!$html || $contact['preferred_mail_format'] == 'Text' ||
576 $contact['preferred_mail_format'] == 'Both'
577 ) {
578 // render the &amp; entities in text mode, so that the links work
579 $mailParams['text'] = str_replace('&amp;', '&', $text);
580 }
581 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
582 $contact['preferred_mail_format'] == 'Both'
583 )
584 ) {
585 $mailParams['html'] = $html;
586 }
587 $result = CRM_Utils_Mail::send($mailParams);
588 }
589 }
590 $schedule->free();
591
592 return $result;
593 }
594
595 /**
596 * Add the schedules reminders in the db.
597 *
598 * @param array $params
599 * (reference ) an assoc array of name/value pairs.
600 * @param array $ids
601 * Unused variable.
602 *
603 * @return CRM_Core_DAO_ActionSchedule
604 */
605 public static function add(&$params, $ids = array()) {
606 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
607 $actionSchedule->copyValues($params);
608
609 return $actionSchedule->save();
610 }
611
612 /**
613 * Retrieve DB object based on input parameters.
614 *
615 * It also stores all the retrieved values in the default array.
616 *
617 * @param array $params
618 * (reference ) an assoc array of name/value pairs.
619 * @param array $values
620 * (reference ) an assoc array to hold the flattened values.
621 *
622 * @return CRM_Core_DAO_ActionSchedule|null
623 * object on success, null otherwise
624 */
625 public static function retrieve(&$params, &$values) {
626 if (empty($params)) {
627 return NULL;
628 }
629 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
630
631 $actionSchedule->copyValues($params);
632
633 if ($actionSchedule->find(TRUE)) {
634 $ids['actionSchedule'] = $actionSchedule->id;
635
636 CRM_Core_DAO::storeValues($actionSchedule, $values);
637
638 return $actionSchedule;
639 }
640 return NULL;
641 }
642
643 /**
644 * Delete a Reminder.
645 *
646 * @param int $id
647 * ID of the Reminder to be deleted.
648 *
649 */
650 public static function del($id) {
651 if ($id) {
652 $dao = new CRM_Core_DAO_ActionSchedule();
653 $dao->id = $id;
654 if ($dao->find(TRUE)) {
655 $dao->delete();
656 return;
657 }
658 }
659 CRM_Core_Error::fatal(ts('Invalid value passed to delete function.'));
660 }
661
662 /**
663 * Update the is_active flag in the db.
664 *
665 * @param int $id
666 * Id of the database record.
667 * @param bool $is_active
668 * Value we want to set the is_active field.
669 *
670 * @return Object
671 * DAO object on success, null otherwise
672 */
673 public static function setIsActive($id, $is_active) {
674 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
675 }
676
677 /**
678 * @param int $mappingID
679 * @param $now
680 *
681 * @throws CRM_Core_Exception
682 */
683 public static function sendMailings($mappingID, $now) {
684 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
685 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
686
687 $mapping = new CRM_Core_DAO_ActionMapping();
688 $mapping->id = $mappingID;
689 $mapping->find(TRUE);
690
691 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
692 $actionSchedule->mapping_id = $mappingID;
693 $actionSchedule->is_active = 1;
694 $actionSchedule->find(FALSE);
695
696 $tokenFields = array();
697 $session = CRM_Core_Session::singleton();
698
699 while ($actionSchedule->fetch()) {
700 $extraSelect = $extraJoin = $extraWhere = $extraOn = '';
701
702 if ($actionSchedule->from_email) {
703 $fromEmailAddress = "$actionSchedule->from_name <$actionSchedule->from_email>";
704 }
705
706 $activityTypeID = FALSE;
707 $activityStatusID = FALSE;
708 if ($actionSchedule->record_activity) {
709 if ($mapping->entity == 'civicrm_membership') {
710 $activityTypeID
711 = CRM_Core_OptionGroup::getValue('activity_type', 'Membership Renewal Reminder', 'name');
712 }
713 else {
714 $activityTypeID
715 = CRM_Core_OptionGroup::getValue('activity_type', 'Reminder Sent', 'name');
716 }
717
718 $activityStatusID
719 = CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name');
720 }
721
722 if ($mapping->entity == 'civicrm_activity') {
723 $compInfo = CRM_Core_Component::getEnabledComponents();
724 $tokenEntity = 'activity';
725 $tokenFields = array('activity_id', 'activity_type', 'subject', 'details', 'activity_date_time');
726 $extraSelect = ', ov.label as activity_type, e.id as activity_id';
727 $extraJoin = "
728 INNER JOIN civicrm_option_group og ON og.name = 'activity_type'
729 INNER JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
730 $extraOn = ' AND e.is_current_revision = 1 AND e.is_deleted = 0 ';
731 if ($actionSchedule->limit_to == 0) {
732 $extraJoin = "
733 LEFT JOIN civicrm_option_group og ON og.name = 'activity_type'
734 LEFT JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
735 }
736
737 //join for caseId
738 // if CiviCase component is enabled
739 if (array_key_exists('CiviCase', $compInfo)) {
740 $extraSelect .= ", civicrm_case_activity.case_id as case_id";
741 $extraJoin .= "
742 LEFT JOIN `civicrm_case_activity` ON `e`.`id` = `civicrm_case_activity`.`activity_id`";
743 }
744 }
745
746 if ($mapping->entity == 'civicrm_participant') {
747 $tokenEntity = 'event';
748 $tokenFields = array(
749 'event_type',
750 'title',
751 'event_id',
752 'start_date',
753 'end_date',
754 'summary',
755 'description',
756 'location',
757 'info_url',
758 'registration_url',
759 'fee_amount',
760 'contact_email',
761 'contact_phone',
762 'balance',
763 );
764 $extraSelect = ', ov.label as event_type, ev.title, ev.id as event_id, ev.start_date, ev.end_date, ev.summary, ev.description, address.street_address, address.city, address.state_province_id, address.postal_code, email.email as contact_email, phone.phone as contact_phone ';
765
766 $extraJoin = "
767 INNER JOIN civicrm_event ev ON e.event_id = ev.id
768 INNER JOIN civicrm_option_group og ON og.name = 'event_type'
769 INNER JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
770 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
771 LEFT JOIN civicrm_address address ON address.id = lb.address_id
772 LEFT JOIN civicrm_email email ON email.id = lb.email_id
773 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
774 ";
775 if ($actionSchedule->limit_to == 0) {
776 $extraJoin = "
777 LEFT JOIN civicrm_event ev ON e.event_id = ev.id
778 LEFT JOIN civicrm_option_group og ON og.name = 'event_type'
779 LEFT JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
780 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
781 LEFT JOIN civicrm_address address ON address.id = lb.address_id
782 LEFT JOIN civicrm_email email ON email.id = lb.email_id
783 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
784 ";
785 }
786 }
787
788 if ($mapping->entity == 'civicrm_membership') {
789 $tokenEntity = 'membership';
790 $tokenFields = array('fee', 'id', 'join_date', 'start_date', 'end_date', 'status', 'type');
791 $extraSelect = ', mt.minimum_fee as fee, e.id as id , e.join_date, e.start_date, e.end_date, ms.name as status, mt.name as type';
792 $extraJoin = '
793 INNER JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
794 INNER JOIN civicrm_membership_status ms ON e.status_id = ms.id';
795
796 if ($actionSchedule->limit_to == 0) {
797 $extraJoin = '
798 LEFT JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
799 LEFT JOIN civicrm_membership_status ms ON e.status_id = ms.id';
800 }
801 }
802
803 if ($mapping->entity == 'civicrm_contact') {
804 $tokenEntity = 'contact';
805 //TODO: get full list somewhere!
806 $tokenFields = array('birth_date', 'last_name');
807 //TODO: is there anything to add here?
808 }
809
810 $entityJoinClause = "INNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
811 if ($actionSchedule->limit_to == 0) {
812 $entityJoinClause = "LEFT JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
813 $extraWhere .= " AND (e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact')";
814 }
815 $entityJoinClause .= $extraOn;
816
817 $query = "
818 SELECT reminder.id as reminderID, reminder.contact_id as contactID, reminder.entity_table as entityTable, reminder.*, e.id as entityID, e.* {$extraSelect}
819 FROM civicrm_action_log reminder
820 {$entityJoinClause}
821 {$extraJoin}
822 WHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL
823 {$extraWhere}";
824
825 $dao = CRM_Core_DAO::executeQuery($query,
826 array(1 => array($actionSchedule->id, 'Integer'))
827 );
828
829 while ($dao->fetch()) {
830 $entityTokenParams = array();
831 foreach ($tokenFields as $field) {
832 if ($field == 'location') {
833 $loc = array();
834 $stateProvince = CRM_Core_PseudoConstant::stateProvince();
835 $loc['street_address'] = $dao->street_address;
836 $loc['city'] = $dao->city;
837 $loc['state_province'] = CRM_Utils_Array::value($dao->state_province_id, $stateProvince);
838 $loc['postal_code'] = $dao->postal_code;
839 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address::format($loc);
840 }
841 elseif ($field == 'info_url') {
842 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE);
843 }
844 elseif ($field == 'registration_url') {
845 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE);
846 }
847 elseif (in_array($field, array('start_date', 'end_date', 'join_date', 'activity_date_time'))) {
848 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date::customFormat($dao->$field);
849 }
850 elseif ($field == 'balance') {
851 if ($dao->entityTable == 'civicrm_contact') {
852 $balancePay = 'N/A';
853 }
854 elseif (!empty($dao->entityID)) {
855 $info = CRM_Contribute_BAO_Contribution::getPaymentInfo($dao->entityID, 'event');
856 $balancePay = CRM_Utils_Array::value('balance', $info);
857 $balancePay = CRM_Utils_Money::format($balancePay);
858 }
859 $entityTokenParams["{$tokenEntity}." . $field] = $balancePay;
860 }
861 elseif ($field == 'fee_amount') {
862 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Money::format($dao->$field);
863 }
864 else {
865 $entityTokenParams["{$tokenEntity}." . $field] = $dao->$field;
866 }
867 }
868
869 $isError = 0;
870 $errorMsg = $toEmail = $toPhoneNumber = '';
871
872 if ($actionSchedule->mode == 'SMS' or $actionSchedule->mode == 'User_Preference') {
873 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
874 $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($dao->contactID, FALSE, 'Mobile', $filters);
875 //to get primary mobile ph,if not get a first mobile phONE
876 if (!empty($toPhoneNumbers)) {
877 $toPhoneNumberDetails = reset($toPhoneNumbers);
878 $toPhoneNumber = CRM_Utils_Array::value('phone', $toPhoneNumberDetails);
879 //contact allows to send sms
880 $toDoNotSms = 0;
881 }
882 }
883 if ($actionSchedule->mode == 'Email' or $actionSchedule->mode == 'User_Preference') {
884 $toEmail = CRM_Contact_BAO_Contact::getPrimaryEmail($dao->contactID);
885 }
886 if ($toEmail || !(empty($toPhoneNumber) or $toDoNotSms)) {
887 $to['email'] = $toEmail;
888 $to['phone'] = $toPhoneNumber;
889 $result
890 = CRM_Core_BAO_ActionSchedule::sendReminder(
891 $dao->contactID,
892 $to,
893 $actionSchedule->id,
894 $fromEmailAddress,
895 $entityTokenParams
896 );
897
898 if (!$result || is_a($result, 'PEAR_Error')) {
899 // we could not send an email, for now we ignore, CRM-3406
900 $isError = 1;
901 }
902 }
903 else {
904 $isError = 1;
905 $errorMsg = "Couldn\'t find recipient\'s email address.";
906 }
907
908 // update action log record
909 $logParams = array(
910 'id' => $dao->reminderID,
911 'is_error' => $isError,
912 'message' => $errorMsg ? $errorMsg : "null",
913 'action_date_time' => $now,
914 );
915 CRM_Core_BAO_ActionLog::create($logParams);
916
917 // insert activity log record if needed
918 if ($actionSchedule->record_activity && !$isError) {
919 $activityParams = array(
920 'subject' => $actionSchedule->title,
921 'details' => $actionSchedule->body_html,
922 'source_contact_id' => $session->get('userID') ? $session->get('userID') : $dao->contactID,
923 'target_contact_id' => $dao->contactID,
924 'activity_date_time' => date('YmdHis'),
925 'status_id' => $activityStatusID,
926 'activity_type_id' => $activityTypeID,
927 'source_record_id' => $dao->entityID,
928 );
929 $activity = CRM_Activity_BAO_Activity::create($activityParams);
930
931 //file reminder on case if source activity is a case activity
932 if (!empty($dao->case_id)) {
933 $caseActivityParams = array();
934 $caseActivityParams['case_id'] = $dao->case_id;
935 $caseActivityParams['activity_id'] = $activity->id;
936 CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
937 }
938 }
939 }
940
941 $dao->free();
942 }
943 }
944
945 /**
946 * @param int $mappingID
947 * @param $now
948 * @param array $params
949 *
950 * @throws API_Exception
951 */
952 public static function buildRecipientContacts($mappingID, $now, $params = array()) {
953 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
954 $actionSchedule->mapping_id = $mappingID;
955 $actionSchedule->is_active = 1;
956 if (!empty($params)) {
957 _civicrm_api3_dao_set_filter($actionSchedule, $params, FALSE);
958 }
959 $actionSchedule->find();
960
961 while ($actionSchedule->fetch()) {
962 $mapping = new CRM_Core_DAO_ActionMapping();
963 $mapping->id = $mappingID;
964 $mapping->find(TRUE);
965
966 // note: $where - this filtering applies for both
967 // 'limit to' and 'addition to' options
968 // $limitWhere - this filtering applies only for
969 // 'limit to' option
970 $select = $join = $where = $limitWhere = array();
971 $selectColumns = "contact_id, entity_id, entity_table, action_schedule_id";
972 $limitTo = $actionSchedule->limit_to;
973 $value = explode(CRM_Core_DAO::VALUE_SEPARATOR,
974 trim($actionSchedule->entity_value, CRM_Core_DAO::VALUE_SEPARATOR)
975 );
976 $value = implode(',', $value);
977
978 $status = explode(CRM_Core_DAO::VALUE_SEPARATOR,
979 trim($actionSchedule->entity_status, CRM_Core_DAO::VALUE_SEPARATOR)
980 );
981 $status = implode(',', $status);
982
983 $anniversary = FALSE;
984
985 if (!CRM_Utils_System::isNull($mapping->entity_recipient)) {
986 if ($mapping->entity_recipient == 'event_contacts') {
987 $recipientOptions = CRM_Core_OptionGroup::values($mapping->entity_recipient, FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
988 }
989 else {
990 $recipientOptions = CRM_Core_OptionGroup::values($mapping->entity_recipient, FALSE, FALSE, FALSE, NULL, 'name');
991 }
992 }
993 $from = "{$mapping->entity} e";
994
995 if ($mapping->entity == 'civicrm_activity') {
996 $contactField = 'r.contact_id';
997 $table = 'civicrm_activity e';
998 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
999 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1000 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1001 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1002
1003 if (!is_null($limitTo)) {
1004 if ($limitTo == 0) {
1005 // including the activity target contacts if 'in addition' is defined
1006 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
1007 }
1008 else {
1009 switch (CRM_Utils_Array::value($actionSchedule->recipient, $recipientOptions)) {
1010 case 'Activity Assignees':
1011 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$assigneeID}";
1012 break;
1013
1014 case 'Activity Source':
1015 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$sourceID}";
1016 break;
1017
1018 default:
1019 case 'Activity Targets':
1020 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
1021 break;
1022 }
1023 }
1024 }
1025 // build where clause
1026 if (!empty($value)) {
1027 $where[] = "e.activity_type_id IN ({$value})";
1028 }
1029 else {
1030 $where[] = "e.activity_type_id IS NULL";
1031 }
1032 if (!empty($status)) {
1033 $where[] = "e.status_id IN ({$status})";
1034 }
1035 $where[] = ' e.is_current_revision = 1 ';
1036 $where[] = ' e.is_deleted = 0 ';
1037
1038 $dateField = 'e.activity_date_time';
1039 }
1040
1041 if ($mapping->entity == 'civicrm_participant') {
1042 $table = 'civicrm_event r';
1043 $contactField = 'e.contact_id';
1044 $join[] = 'INNER JOIN civicrm_event r ON e.event_id = r.id';
1045 if ($actionSchedule->recipient_listing && $limitTo) {
1046 $rList = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1047 trim($actionSchedule->recipient_listing, CRM_Core_DAO::VALUE_SEPARATOR)
1048 );
1049 $rList = implode(',', $rList);
1050
1051 switch (CRM_Utils_Array::value($actionSchedule->recipient, $recipientOptions)) {
1052 case 'participant_role':
1053 $where[] = "e.role_id IN ({$rList})";
1054 break;
1055
1056 default:
1057 break;
1058 }
1059 }
1060
1061 // build where clause
1062 if (!empty($value)) {
1063 $where[] = ($mapping->entity_value == 'event_type') ? "r.event_type_id IN ({$value})" : "r.id IN ({$value})";
1064 }
1065 else {
1066 $where[] = ($mapping->entity_value == 'event_type') ? "r.event_type_id IS NULL" : "r.id IS NULL";
1067 }
1068
1069 // participant status criteria not to be implemented
1070 // for additional recipients
1071 if (!empty($status)) {
1072 $limitWhere[] = "e.status_id IN ({$status})";
1073 }
1074
1075 $where[] = 'r.is_active = 1';
1076 $where[] = 'r.is_template = 0';
1077 $dateField = str_replace('event_', 'r.', $actionSchedule->start_action_date);
1078 }
1079
1080 $notINClause = '';
1081 if ($mapping->entity == 'civicrm_membership') {
1082 $contactField = 'e.contact_id';
1083 $table = 'civicrm_membership e';
1084 // build where clause
1085 if ($status == 2) {
1086 //auto-renew memberships
1087 $where[] = "e.contribution_recur_id IS NOT NULL ";
1088 }
1089 elseif ($status == 1) {
1090 $where[] = "e.contribution_recur_id IS NULL ";
1091 }
1092
1093 // build where clause
1094 if (!empty($value)) {
1095 $where[] = "e.membership_type_id IN ({$value})";
1096 }
1097 else {
1098 $where[] = "e.membership_type_id IS NULL";
1099 }
1100
1101 $where[] = "( e.is_override IS NULL OR e.is_override = 0 )";
1102 $dateField = str_replace('membership_', 'e.', $actionSchedule->start_action_date);
1103 $notINClause = self::permissionedRelationships($contactField);
1104
1105 $membershipStatus = CRM_Member_PseudoConstant::membershipStatus(NULL, "(is_current_member = 1 OR name = 'Expired')", 'id');
1106 $mStatus = implode(',', $membershipStatus);
1107 $where[] = "e.status_id IN ({$mStatus})";
1108
1109 // We are not tracking the reference date for 'repeated' schedule reminders,
1110 // for further details please check CRM-15376
1111 if ($actionSchedule->start_action_date && $actionSchedule->is_repeat == FALSE) {
1112 $select[] = $dateField;
1113 $selectColumns = "reference_date, " . $selectColumns;
1114 }
1115 }
1116
1117 if ($mapping->entity == 'civicrm_contact') {
1118 $contactFields = array(
1119 'birth_date',
1120 'created_date',
1121 'modified_date',
1122 );
1123 if (in_array($value, $contactFields)) {
1124 $dateDBField = $value;
1125 $table = 'civicrm_contact e';
1126 $contactField = 'e.id';
1127 $where[] = 'e.is_deleted = 0';
1128 $where[] = 'e.is_deceased = 0';
1129 }
1130 else {
1131 //custom field
1132 $customFieldParams = array('id' => substr($value, 7));
1133 $customGroup = $customField = array();
1134 CRM_Core_BAO_CustomField::retrieve($customFieldParams, $customField);
1135 $dateDBField = $customField['column_name'];
1136 $customGroupParams = array('id' => $customField['custom_group_id'], $customGroup);
1137 CRM_Core_BAO_CustomGroup::retrieve($customGroupParams, $customGroup);
1138 $from = $table = "{$customGroup['table_name']} e";
1139 $contactField = 'e.entity_id';
1140 $where[] = '1'; // possible to have no "where" in this case
1141 }
1142
1143 $status_ = explode(',', $status);
1144 if (in_array(2, $status_)) {
1145 // anniversary mode:
1146 $dateField = 'DATE_ADD(e.' . $dateDBField . ', INTERVAL ROUND(DATEDIFF(DATE(' . $now . '), e.' . $dateDBField . ') / 365) YEAR)';
1147 $anniversary = TRUE;
1148 }
1149 else {
1150 // regular mode:
1151 $dateField = 'e.' . $dateDBField;
1152 }
1153 }
1154
1155 // CRM-13577 Introduce Smart Groups Handling
1156 if ($actionSchedule->group_id) {
1157
1158 // Need to check if its a smart group or not
1159 // Then decide which table to join onto the query
1160 $group = CRM_Contact_DAO_Group::getTableName();
1161
1162 // Get the group information
1163 $sql = "
1164 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
1165 FROM $group
1166 WHERE $group.id = {$actionSchedule->group_id}
1167 ";
1168
1169 $groupDAO = CRM_Core_DAO::executeQuery($sql);
1170 $isSmartGroup = FALSE;
1171 if (
1172 $groupDAO->fetch() &&
1173 !empty($groupDAO->saved_search_id)
1174 ) {
1175 // Check that the group is in place in the cache and up to date
1176 CRM_Contact_BAO_GroupContactCache::check($actionSchedule->group_id);
1177 // Set smart group flag
1178 $isSmartGroup = TRUE;
1179 }
1180 }
1181 // CRM-13577 End Introduce Smart Groups Handling
1182
1183 if ($limitTo) {
1184 if ($actionSchedule->group_id) {
1185 // CRM-13577 If smart group then use Cache table
1186 if ($isSmartGroup) {
1187 $join[] = "INNER JOIN civicrm_group_contact_cache grp ON {$contactField} = grp.contact_id";
1188 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1189 }
1190 else {
1191 $join[] = "INNER JOIN civicrm_group_contact grp ON {$contactField} = grp.contact_id AND grp.status = 'Added'";
1192 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1193 }
1194 }
1195 elseif (!empty($actionSchedule->recipient_manual)) {
1196 $rList = CRM_Utils_Type::escape($actionSchedule->recipient_manual, 'String');
1197 $where[] = "{$contactField} IN ({$rList})";
1198 }
1199 }
1200 elseif (!is_null($limitTo)) {
1201 $addGroup = $addWhere = '';
1202 if ($actionSchedule->group_id) {
1203 // CRM-13577 If smart group then use Cache table
1204 if ($isSmartGroup) {
1205 $addGroup = " INNER JOIN civicrm_group_contact_cache grp ON c.id = grp.contact_id";
1206 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1207 }
1208 else {
1209 $addGroup = " INNER JOIN civicrm_group_contact grp ON c.id = grp.contact_id AND grp.status = 'Added'";
1210 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1211 }
1212 }
1213 if (!empty($actionSchedule->recipient_manual)) {
1214 $rList = CRM_Utils_Type::escape($actionSchedule->recipient_manual, 'String');
1215 $addWhere = "c.id IN ({$rList})";
1216 }
1217 }
1218
1219 $select[] = "{$contactField} as contact_id";
1220 $select[] = 'e.id as entity_id';
1221 $select[] = "'{$mapping->entity}' as entity_table";
1222 $select[] = "{$actionSchedule->id} as action_schedule_id";
1223 $reminderJoinClause = "civicrm_action_log reminder ON reminder.contact_id = {$contactField} AND
1224 reminder.entity_id = e.id AND
1225 reminder.entity_table = '{$mapping->entity}' AND
1226 reminder.action_schedule_id = %1";
1227
1228 if ($anniversary) {
1229 // only consider reminders less than 11 months ago
1230 $reminderJoinClause .= " AND reminder.action_date_time > DATE_SUB({$now}, INTERVAL 11 MONTH)";
1231 }
1232
1233 if ($table != 'civicrm_contact e') {
1234 $join[] = "INNER JOIN civicrm_contact c ON c.id = {$contactField} AND c.is_deleted = 0 AND c.is_deceased = 0 ";
1235 }
1236
1237 if ($actionSchedule->start_action_date) {
1238 $startDateClause = array();
1239 $op = ($actionSchedule->start_action_condition == 'before' ? '<=' : '>=');
1240 $operator = ($actionSchedule->start_action_condition == 'before' ? 'DATE_SUB' : 'DATE_ADD');
1241 $date = $operator . "({$dateField}, INTERVAL {$actionSchedule->start_action_offset} {$actionSchedule->start_action_unit})";
1242 $startDateClause[] = "'{$now}' >= {$date}";
1243 if ($mapping->entity == 'civicrm_participant') {
1244 $startDateClause[] = $operator . "({$now}, INTERVAL 1 DAY ) {$op} " . $dateField;
1245 }
1246 else {
1247 $startDateClause[] = "DATE_SUB({$now}, INTERVAL 1 DAY ) <= {$date}";
1248 }
1249
1250 $startDate = implode(' AND ', $startDateClause);
1251 }
1252 elseif ($actionSchedule->absolute_date) {
1253 $startDate = "DATEDIFF(DATE('{$now}'),'{$actionSchedule->absolute_date}') = 0";
1254 }
1255
1256 // ( now >= date_built_from_start_time ) OR ( now = absolute_date )
1257 $dateClause = "reminder.id IS NULL AND {$startDate}";
1258
1259 // start composing query
1260 $selectClause = 'SELECT ' . implode(', ', $select);
1261 $fromClause = "FROM $from";
1262 $joinClause = !empty($join) ? implode(' ', $join) : '';
1263 $whereClause = 'WHERE ' . implode(' AND ', $where);
1264 $limitWhereClause = '';
1265 if (!empty($limitWhere)) {
1266 $limitWhereClause = ' AND ' . implode(' AND ', $limitWhere);
1267 }
1268
1269 $query = "
1270 INSERT INTO civicrm_action_log ({$selectColumns})
1271 {$selectClause}
1272 {$fromClause}
1273 {$joinClause}
1274 LEFT JOIN {$reminderJoinClause}
1275 {$whereClause} {$limitWhereClause} AND {$dateClause} {$notINClause}
1276 ";
1277
1278 // In some cases reference_date got outdated due to many reason e.g. In Membership renewal end_date got extended
1279 // which means reference date mismatches with the end_date where end_date may be used as the start_action_date
1280 // criteria for some schedule reminder so in order to send new reminder we INSERT new reminder with new reference_date
1281 // value via UNION operation
1282 if (strpos($selectColumns, 'reference_date') !== FALSE) {
1283 $dateClause = str_replace('reminder.id IS NULL', 'reminder.id IS NOT NULL', $dateClause);
1284 $referenceQuery = "
1285 INSERT INTO civicrm_action_log ({$selectColumns})
1286 {$selectClause}
1287 {$fromClause}
1288 {$joinClause}
1289 LEFT JOIN {$reminderJoinClause}
1290 {$whereClause} {$limitWhereClause} {$notINClause} AND {$dateClause} AND
1291 reminder.action_date_time IS NOT NULL AND
1292 reminder.reference_date IS NOT NULL
1293 GROUP BY reminder.id, reminder.reference_date
1294 HAVING reminder.id = MAX(reminder.id) AND reminder.reference_date <> {$dateField}
1295 ";
1296 }
1297
1298 CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer')));
1299
1300 if (!empty($referenceQuery)) {
1301 CRM_Core_DAO::executeQuery($referenceQuery, array(1 => array($actionSchedule->id, 'Integer')));
1302 }
1303
1304 $isSendToAdditionalContacts = (!is_null($limitTo) && $limitTo == 0 && (!empty($addGroup) || !empty($addWhere))) ? TRUE : FALSE;
1305 if ($isSendToAdditionalContacts) {
1306 $contactTable = "civicrm_contact c";
1307 $addSelect = "SELECT c.id as contact_id, c.id as entity_id, 'civicrm_contact' as entity_table, {$actionSchedule->id} as action_schedule_id";
1308 $additionReminderClause = "civicrm_action_log reminder ON reminder.contact_id = c.id AND
1309 reminder.entity_id = c.id AND
1310 reminder.entity_table = 'civicrm_contact' AND
1311 reminder.action_schedule_id = {$actionSchedule->id}";
1312 $addWhereClause = '';
1313 if ($addWhere) {
1314 $addWhereClause = "AND {$addWhere}";
1315 }
1316 $insertAdditionalSql = "
1317 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1318 {$addSelect}
1319 FROM ({$contactTable})
1320 LEFT JOIN {$additionReminderClause}
1321 {$addGroup}
1322 WHERE c.is_deleted = 0 AND c.is_deceased = 0
1323 {$addWhereClause}
1324
1325 AND c.id NOT IN (
1326 SELECT rem.contact_id
1327 FROM civicrm_action_log rem INNER JOIN {$mapping->entity} e ON rem.entity_id = e.id
1328 WHERE rem.action_schedule_id = {$actionSchedule->id}
1329 AND rem.entity_table = '{$mapping->entity}'
1330 )
1331 GROUP BY c.id
1332 ";
1333 CRM_Core_DAO::executeQuery($insertAdditionalSql);
1334 }
1335 // if repeat is turned ON:
1336 if ($actionSchedule->is_repeat) {
1337 $repeatEvent = ($actionSchedule->end_action == 'before' ? 'DATE_SUB' : 'DATE_ADD') . "({$dateField}, INTERVAL {$actionSchedule->end_frequency_interval} {$actionSchedule->end_frequency_unit})";
1338
1339 if ($actionSchedule->repetition_frequency_unit == 'day') {
1340 $interval = "{$actionSchedule->repetition_frequency_interval} DAY";
1341 }
1342 elseif ($actionSchedule->repetition_frequency_unit == 'week') {
1343 $interval = "{$actionSchedule->repetition_frequency_interval} WEEK";
1344 }
1345 elseif ($actionSchedule->repetition_frequency_unit == 'month') {
1346 $interval = "{$actionSchedule->repetition_frequency_interval} MONTH";
1347 }
1348 elseif ($actionSchedule->repetition_frequency_unit == 'year') {
1349 $interval = "{$actionSchedule->repetition_frequency_interval} YEAR";
1350 }
1351 else {
1352 $interval = "{$actionSchedule->repetition_frequency_interval} HOUR";
1353 }
1354
1355 // (now <= repeat_end_time )
1356 $repeatEventClause = "'{$now}' <= {$repeatEvent}";
1357 // diff(now && logged_date_time) >= repeat_interval
1358 $havingClause = "HAVING TIMESTAMPDIFF(HOUR, latest_log_time, CAST({$now} AS datetime)) >= TIMESTAMPDIFF(HOUR, latest_log_time, DATE_ADD(latest_log_time, INTERVAL $interval))";
1359 $groupByClause = 'GROUP BY reminder.contact_id, reminder.entity_id, reminder.entity_table';
1360 $selectClause .= ', MAX(reminder.action_date_time) as latest_log_time';
1361 //CRM-15376 - do not send our reminders if original criteria no longer applies
1362 // the first part of the startDateClause array is the earliest the reminder can be sent. If the
1363 // event (e.g membership_end_date) has changed then the reminder may no longer apply
1364 // @todo - this only handles events that get moved later. Potentially they might get moved earlier
1365 $originalEventStartDateClause = empty($startDateClause) ? '' : 'AND' . $startDateClause[0];
1366 $sqlInsertValues = "{$selectClause}
1367 {$fromClause}
1368 {$joinClause}
1369 INNER JOIN {$reminderJoinClause}
1370 {$whereClause} {$limitWhereClause} AND {$repeatEventClause} {$originalEventStartDateClause} {$notINClause}
1371 {$groupByClause}
1372 {$havingClause}";
1373
1374 $valsqlInsertValues = CRM_Core_DAO::executeQuery($sqlInsertValues, array(
1375 1 => array(
1376 $actionSchedule->id,
1377 'Integer',
1378 ),
1379 )
1380 );
1381
1382 $arrValues = array();
1383 while ($valsqlInsertValues->fetch()) {
1384 $arrValues[] = "( {$valsqlInsertValues->contact_id}, {$valsqlInsertValues->entity_id}, '{$valsqlInsertValues->entity_table}',{$valsqlInsertValues->action_schedule_id} )";
1385 }
1386
1387 $valString = implode(',', $arrValues);
1388
1389 if ($valString) {
1390 $query = '
1391 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1392 CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer')));
1393 }
1394
1395 if ($isSendToAdditionalContacts) {
1396 $addSelect .= ', MAX(reminder.action_date_time) as latest_log_time';
1397 $sqlEndEventCheck = "
1398 SELECT * FROM {$table}
1399 {$whereClause} AND {$repeatEventClause} LIMIT 1";
1400
1401 $daoCheck = CRM_Core_DAO::executeQuery($sqlEndEventCheck);
1402 if ($daoCheck->fetch()) {
1403 $valSqlAdditionInsert = "
1404 {$addSelect}
1405 FROM {$contactTable}
1406 {$addGroup}
1407 INNER JOIN {$additionReminderClause}
1408 WHERE {$addWhere} AND c.is_deleted = 0 AND c.is_deceased = 0
1409 GROUP BY reminder.contact_id
1410 {$havingClause}
1411 ";
1412 $daoForVals = CRM_Core_DAO::executeQuery($valSqlAdditionInsert);
1413 $addValues = array();
1414 while ($daoForVals->fetch()) {
1415 $addValues[] = "( {$daoForVals->contact_id}, {$daoForVals->entity_id}, '{$daoForVals->entity_table}',{$daoForVals->action_schedule_id} )";
1416 }
1417 $valString = implode(',', $addValues);
1418
1419 if ($valString) {
1420 $query = '
1421 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1422 CRM_Core_DAO::executeQuery($query);
1423 }
1424 }
1425 }
1426 }
1427 }
1428 }
1429
1430 /**
1431 * @param $field
1432 *
1433 * @return null|string
1434 */
1435 public static function permissionedRelationships($field) {
1436 $query = '
1437 SELECT cm.id AS owner_id, cm.contact_id AS owner_contact, m.id AS slave_id, m.contact_id AS slave_contact, cmt.relationship_type_id AS relation_type, rel.contact_id_a, rel.contact_id_b, rel.is_permission_a_b, rel.is_permission_b_a
1438 FROM civicrm_membership m
1439 LEFT JOIN civicrm_membership cm ON cm.id = m.owner_membership_id
1440 LEFT JOIN civicrm_membership_type cmt ON cmt.id = m.membership_type_id
1441 LEFT JOIN civicrm_relationship rel ON ( ( rel.contact_id_a = m.contact_id AND rel.contact_id_b = cm.contact_id AND rel.relationship_type_id = cmt.relationship_type_id )
1442 OR ( rel.contact_id_a = cm.contact_id AND rel.contact_id_b = m.contact_id AND rel.relationship_type_id = cmt.relationship_type_id ) )
1443 WHERE m.owner_membership_id IS NOT NULL AND
1444 ( rel.is_permission_a_b = 0 OR rel.is_permission_b_a = 0)
1445
1446 ';
1447 $excludeIds = array();
1448 $dao = CRM_Core_DAO::executeQuery($query, array());
1449 while ($dao->fetch()) {
1450 if ($dao->slave_contact == $dao->contact_id_a && $dao->is_permission_a_b == 0) {
1451 $excludeIds[] = $dao->slave_contact;
1452 }
1453 elseif ($dao->slave_contact == $dao->contact_id_b && $dao->is_permission_b_a == 0) {
1454 $excludeIds[] = $dao->slave_contact;
1455 }
1456 }
1457
1458 if (!empty($excludeIds)) {
1459 $clause = "AND {$field} NOT IN ( " . implode(', ', $excludeIds) . ' ) ';
1460 return $clause;
1461 }
1462 return NULL;
1463 }
1464
1465 /**
1466 * @param null $now
1467 * @param array $params
1468 *
1469 * @return array
1470 */
1471 public static function processQueue($now = NULL, $params = array()) {
1472 $now = $now ? CRM_Utils_Time::setTime($now) : CRM_Utils_Time::getTime();
1473
1474 $mappings = self::getMapping();
1475 foreach ($mappings as $mappingID => $mapping) {
1476 self::buildRecipientContacts($mappingID, $now, $params);
1477 self::sendMailings($mappingID, $now);
1478 }
1479
1480 $result = array(
1481 'is_error' => 0,
1482 'messages' => ts('Sent all scheduled reminders successfully'),
1483 );
1484 return $result;
1485 }
1486
1487 /**
1488 * @param int $id
1489 * @param int $mappingID
1490 *
1491 * @return null|string
1492 */
1493 public static function isConfigured($id, $mappingID) {
1494 $queryString = "SELECT count(id) FROM civicrm_action_schedule
1495 WHERE mapping_id = %1 AND
1496 entity_value = %2";
1497
1498 $params = array(
1499 1 => array($mappingID, 'Integer'),
1500 2 => array($id, 'Integer'),
1501 );
1502 return CRM_Core_DAO::singleValueQuery($queryString, $params);
1503 }
1504
1505 /**
1506 * @param int $mappingID
1507 * @param $recipientType
1508 *
1509 * @return array
1510 */
1511 public static function getRecipientListing($mappingID, $recipientType) {
1512 $options = array();
1513 if (!$mappingID || !$recipientType) {
1514 return $options;
1515 }
1516
1517 $mapping = self::getMapping($mappingID);
1518
1519 switch ($mapping['entity']) {
1520 case 'civicrm_participant':
1521 $eventContacts = CRM_Core_OptionGroup::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
1522 if (empty($eventContacts[$recipientType])) {
1523 return $options;
1524 }
1525 if ($eventContacts[$recipientType] == 'participant_role') {
1526 $options = CRM_Event_PseudoConstant::participantRole();
1527 }
1528 break;
1529 }
1530
1531 return $options;
1532 }
1533
1534 }