3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
37 * This class contains functions for managing Scheduled Reminders
39 class CRM_Core_BAO_ActionSchedule
extends CRM_Core_DAO_ActionSchedule
{
46 public static function getMapping($id = NULL) {
47 static $_action_mapping;
49 if ($id && !is_null($_action_mapping) && isset($_action_mapping[$id])) {
50 return $_action_mapping[$id];
53 $dao = new CRM_Core_DAO_ActionMapping();
60 while ($dao->fetch()) {
62 CRM_Core_DAO
::storeValues($dao, $defaults);
63 $mapping[$dao->id
] = $defaults;
65 $_action_mapping = $mapping;
71 * Get all fields of the type Date.
73 public static function getDateFields() {
74 $allFields = CRM_Core_BAO_CustomField
::getFields('');
76 'birth_date' => ts('Birth Date'),
77 'created_date' => ts('Created Date'),
78 'modified_date' => ts('Modified Date'),
80 foreach ($allFields as $fieldID => $field) {
81 if ($field['data_type'] == 'Date') {
82 $dateFields["custom_$fieldID"] = $field['label'];
89 * Retrieve list of selections/drop downs for Scheduled Reminder form
95 * associated array of all the drop downs in the form
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);
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');
112 asort($activityType);
114 $sel1 = $sel2 = $sel3 = $sel4 = $sel5 = array();
116 'manual' => ts('Choose Recipient(s)'),
117 'group' => ts('Select Group'),
120 $entityMapping = array();
121 $recipientMapping = array_combine(array_keys($options), array_keys($options));
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);
136 switch ($entityValue) {
137 case 'activity_type':
138 if ($value['entity'] == 'civicrm_activity') {
139 $sel1Val = ts('Activity');
141 $sel2[$key] = $valueLabel +
$activityType;
145 if ($value['entity'] == 'civicrm_participant') {
146 $sel1Val = ts('Event Type');
148 $sel2[$key] = $valueLabel +
$eventType;
151 case 'event_template':
152 if ($value['entity'] == 'civicrm_participant') {
153 $sel1Val = ts('Event Template');
155 $sel2[$key] = $valueLabel +
$eventTemplate;
158 case 'civicrm_event':
159 if ($value['entity'] == 'civicrm_participant') {
160 $sel1Val = ts('Event Name');
162 $sel2[$key] = $valueLabel +
$event;
165 case 'civicrm_membership_type':
166 if ($value['entity'] == 'civicrm_membership') {
167 $sel1Val = ts('Membership');
169 $sel2[$key] = $valueLabel +
$membershipType;
172 case 'civicrm_contact':
173 if ($value['entity'] == 'civicrm_contact') {
174 $sel1Val = ts('Contact');
176 $sel2[$key] = $dateFields;
179 $sel1[$key] = $sel1Val;
182 if ($startDate = CRM_Utils_Array
::value('entity_date_start', $value)) {
183 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
185 if ($endDate = CRM_Utils_Array
::value('entity_date_end', $value)) {
186 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
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');
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');
203 $sel5[$entityRecipient] = $options;
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);
215 switch ($entityStatus) {
216 case 'activity_status':
217 foreach ($sel3[$id] as $kkey => & $vval) {
218 $vval = $statusLabel +
$activityStatus;
222 case 'civicrm_participant_status_type':
223 foreach ($sel3[$id] as $kkey => & $vval) {
224 $vval = $statusLabel +
$participantStatus;
228 case 'auto_renew_options':
229 foreach ($sel3[$id] as $kkey => & $vval) {
232 $auto = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $kkey, 'auto_renew');
235 $vval = $statusLabel +
$autoRenew;
238 $vval = $statusLabel;
243 case 'contact_date_reminder_options':
244 foreach ($sel3[$id] as $kkey => & $vval) {
245 $vval = $contactOptions;
261 'entityMapping' => $entityMapping,
262 'recipientMapping' => $recipientMapping,
268 * @param int $isLimit
272 public static function getSelection1($id = NULL, $isLimit = NULL) {
273 $mapping = self
::getMapping($id);
274 $sel4 = $sel5 = array();
276 'manual' => ts('Choose Recipient(s)'),
277 'group' => ts('Select Group'),
280 $recipientMapping = array_combine(array_keys($options), array_keys($options));
282 foreach ($mapping as $value) {
283 $entityRecipient = CRM_Utils_Array
::value('entity_recipient', $value);
284 $key = CRM_Utils_Array
::value('id', $value);
286 if ($startDate = CRM_Utils_Array
::value('entity_date_start', $value)) {
287 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
289 if ($endDate = CRM_Utils_Array
::value('entity_date_end', $value)) {
290 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
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');
300 case 'event_contacts':
301 //CRM-15536, don't provide participant_role option on choosing 'Also Include' for Event entity
303 $options +
= CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name');
305 $sel5[$id] = $options;
306 $recipientMapping +
= CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
310 $sel5[$id] = $options;
317 'sel5' => $sel5[$id],
318 'recipientMapping' => $recipientMapping,
323 * Retrieve list of Scheduled Reminders.
325 * @param bool $namesOnly
326 * Return simple list of names.
328 * @param null $entityValue
332 * (reference) reminder list
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();
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();
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();
349 'civicrm_activity' => 'Activity',
350 'civicrm_participant' => 'Event',
351 'civicrm_membership' => 'Member',
352 'civicrm_contact' => 'Contact',
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,
372 FROM civicrm_action_schedule cas
373 LEFT JOIN civicrm_action_mapping cam ON (cam.id = cas.mapping_id)
375 $params = CRM_Core_DAO
::$_nullArray;
376 $where = " WHERE 1 ";
377 if ($entityValue and $id) {
379 AND cas.entity_value = $id AND
380 cam.entity_value = '$entityValue'";
383 1 => array($id, 'Integer'),
384 2 => array($entityValue, 'String'),
387 $where .= " AND cas.used_for IS NULL";
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
;
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);
404 $statusIds = implode(', ', $statusArray);
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);
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
;
423 * @param int $contactId
425 * @param int $scheduleID
427 * @param array $tokenParams
430 * @throws CRM_Core_Exception
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;
438 $domain = CRM_Core_BAO_Domain
::getDomain();
440 $hookTokens = array();
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
;
448 $body_text = CRM_Utils_String
::htmlToText($body_html);
451 $params = array(array('contact_id', '=', $contactId, 0, 0));
452 list($contact, $_) = CRM_Contact_BAO_Query
::apiQuery($params);
455 $contact = reset($contact);
457 if (!$contact ||
is_a($contact, 'CRM_Core_Error')) {
461 // merge activity tokens with contact array
462 $contact = array_merge($contact, $tokenParams);
465 CRM_Utils_Hook
::tokenValues($contact, $contactId);
467 CRM_Utils_Hook
::tokens($hookTokens);
468 $categories = array_keys($hookTokens);
470 $type = array('body_html' => 'html', 'body_text' => 'text', 'sms_body_text' => 'text');
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;
478 $dummy_mail->$bodyType = $
$bodyType;
480 $tokens = $dummy_mail->getTokens();
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);
492 $sms_text = $sms_body_text;
494 $smarty = CRM_Core_Smarty
::singleton();
500 $
$elem = $smarty->fetch("string:{$$elem}");
503 //@todo - this next section is a duplicate of function CRM_Utils_Token::getTokens
505 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
511 $subjectToken = NULL;
513 foreach ($matches[1] as $token) {
514 list($type, $name) = preg_split('/\./', $token, 2);
516 if (!isset($subjectToken[$type])) {
517 $subjectToken[$type] = array();
519 $subjectToken[$type][] = $name;
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);
530 $messageSubject = $smarty->fetch("string:{$messageSubject}");
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;
536 'To' => $phoneNumber,
537 'provider_id' => $schedule->sms_provider_id
,
538 'activity_subject' => $messageSubject,
540 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
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'),
553 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
555 CRM_Activity_BAO_Activity
::sendSMSMessage($contactId,
563 if ($schedule->mode
== 'Email' or $schedule->mode
== 'User_Preference') {
564 // set up the parameters for CRM_Utils_Mail::send
566 'groupName' => 'Scheduled Reminder Sender',
568 'toName' => $contact['display_name'],
570 'subject' => $messageSubject,
571 'entity' => 'action_schedule',
572 'entity_id' => $scheduleID,
575 if (!$html ||
$contact['preferred_mail_format'] == 'Text' ||
576 $contact['preferred_mail_format'] == 'Both'
578 // render the & entities in text mode, so that the links work
579 $mailParams['text'] = str_replace('&', '&', $text);
581 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
582 $contact['preferred_mail_format'] == 'Both'
585 $mailParams['html'] = $html;
587 $result = CRM_Utils_Mail
::send($mailParams);
596 * Add the schedules reminders in the db.
598 * @param array $params
599 * (reference ) an assoc array of name/value pairs.
603 * @return CRM_Core_DAO_ActionSchedule
605 public static function add(&$params, $ids = array()) {
606 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
607 $actionSchedule->copyValues($params);
609 return $actionSchedule->save();
613 * Retrieve DB object based on input parameters.
615 * It also stores all the retrieved values in the default array.
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.
622 * @return CRM_Core_DAO_ActionSchedule|null
623 * object on success, null otherwise
625 public static function retrieve(&$params, &$values) {
626 if (empty($params)) {
629 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
631 $actionSchedule->copyValues($params);
633 if ($actionSchedule->find(TRUE)) {
634 $ids['actionSchedule'] = $actionSchedule->id
;
636 CRM_Core_DAO
::storeValues($actionSchedule, $values);
638 return $actionSchedule;
647 * ID of the Reminder to be deleted.
650 public static function del($id) {
652 $dao = new CRM_Core_DAO_ActionSchedule();
654 if ($dao->find(TRUE)) {
659 CRM_Core_Error
::fatal(ts('Invalid value passed to delete function.'));
663 * Update the is_active flag in the db.
666 * Id of the database record.
667 * @param bool $is_active
668 * Value we want to set the is_active field.
671 * DAO object on success, null otherwise
673 public static function setIsActive($id, $is_active) {
674 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
678 * @param int $mappingID
681 * @throws CRM_Core_Exception
683 public static function sendMailings($mappingID, $now) {
684 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
685 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
687 $mapping = new CRM_Core_DAO_ActionMapping();
688 $mapping->id
= $mappingID;
689 $mapping->find(TRUE);
691 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
692 $actionSchedule->mapping_id
= $mappingID;
693 $actionSchedule->is_active
= 1;
694 $actionSchedule->find(FALSE);
696 $tokenFields = array();
697 $session = CRM_Core_Session
::singleton();
699 while ($actionSchedule->fetch()) {
700 $extraSelect = $extraJoin = $extraWhere = $extraOn = '';
702 if ($actionSchedule->from_email
) {
703 $fromEmailAddress = "$actionSchedule->from_name <$actionSchedule->from_email>";
706 $activityTypeID = FALSE;
707 $activityStatusID = FALSE;
708 if ($actionSchedule->record_activity
) {
709 if ($mapping->entity
== 'civicrm_membership') {
711 = CRM_Core_OptionGroup
::getValue('activity_type', 'Membership Renewal Reminder', 'name');
715 = CRM_Core_OptionGroup
::getValue('activity_type', 'Reminder Sent', 'name');
719 = CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
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';
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) {
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";
738 // if CiviCase component is enabled
739 if (array_key_exists('CiviCase', $compInfo)) {
740 $extraSelect .= ", civicrm_case_activity.case_id as case_id";
742 LEFT JOIN `civicrm_case_activity` ON `e`.`id` = `civicrm_case_activity`.`activity_id`";
746 if ($mapping->entity
== 'civicrm_participant') {
747 $tokenEntity = 'event';
748 $tokenFields = array(
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 ';
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
775 if ($actionSchedule->limit_to
== 0) {
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
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';
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';
796 if ($actionSchedule->limit_to
== 0) {
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';
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?
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')";
815 $entityJoinClause .= $extraOn;
819 SELECT reminder.id as reminderID, reminder.contact_id as contactID, reminder.entity_table as entityTable, reminder.*, e.id as entityID, e.* {$extraSelect}
820 FROM civicrm_action_log reminder
823 WHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL
826 $dao = CRM_Core_DAO
::executeQuery($query,
827 array(1 => array($actionSchedule->id
, 'Integer'))
830 $multilingual = CRM_Core_I18n
::isMultilingual();
831 while ($dao->fetch()) {
832 // switch language if necessary
834 $cid = $dao->contactID
;
835 $preferred_language = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'preferred_language');
836 CRM_Core_BAO_ActionSchedule
::setCommunicationLanguage($actionSchedule->communication_language
, $preferred_language);
839 $entityTokenParams = array();
840 foreach ($tokenFields as $field) {
841 if ($field == 'location') {
843 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
844 $loc['street_address'] = $dao->street_address
;
845 $loc['city'] = $dao->city
;
846 $loc['state_province'] = CRM_Utils_Array
::value($dao->state_province_id
, $stateProvince);
847 $loc['postal_code'] = $dao->postal_code
;
848 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address
::format($loc);
850 elseif ($field == 'info_url') {
851 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
853 elseif ($field == 'registration_url') {
854 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
856 elseif (in_array($field, array('start_date', 'end_date', 'join_date', 'activity_date_time'))) {
857 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date
::customFormat($dao->$field);
859 elseif ($field == 'balance') {
860 if ($dao->entityTable
== 'civicrm_contact') {
863 elseif (!empty($dao->entityID
)) {
864 $info = CRM_Contribute_BAO_Contribution
::getPaymentInfo($dao->entityID
, 'event');
865 $balancePay = CRM_Utils_Array
::value('balance', $info);
866 $balancePay = CRM_Utils_Money
::format($balancePay);
868 $entityTokenParams["{$tokenEntity}." . $field] = $balancePay;
870 elseif ($field == 'fee_amount') {
871 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Money
::format($dao->$field);
874 $entityTokenParams["{$tokenEntity}." . $field] = $dao->$field;
879 $errorMsg = $toEmail = $toPhoneNumber = '';
881 if ($actionSchedule->mode
== 'SMS' or $actionSchedule->mode
== 'User_Preference') {
882 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
883 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($dao->contactID
, FALSE, 'Mobile', $filters);
884 //to get primary mobile ph,if not get a first mobile phONE
885 if (!empty($toPhoneNumbers)) {
886 $toPhoneNumberDetails = reset($toPhoneNumbers);
887 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumberDetails);
888 //contact allows to send sms
892 if ($actionSchedule->mode
== 'Email' or $actionSchedule->mode
== 'User_Preference') {
893 $toEmail = CRM_Contact_BAO_Contact
::getPrimaryEmail($dao->contactID
);
895 if ($toEmail ||
!(empty($toPhoneNumber) or $toDoNotSms)) {
896 $to['email'] = $toEmail;
897 $to['phone'] = $toPhoneNumber;
899 = CRM_Core_BAO_ActionSchedule
::sendReminder(
907 if (!$result ||
is_a($result, 'PEAR_Error')) {
908 // we could not send an email, for now we ignore, CRM-3406
914 $errorMsg = "Couldn\'t find recipient\'s email address.";
917 // update action log record
919 'id' => $dao->reminderID
,
920 'is_error' => $isError,
921 'message' => $errorMsg ?
$errorMsg : "null",
922 'action_date_time' => $now,
924 CRM_Core_BAO_ActionLog
::create($logParams);
926 // insert activity log record if needed
927 if ($actionSchedule->record_activity
&& !$isError) {
928 $activityParams = array(
929 'subject' => $actionSchedule->title
,
930 'details' => $actionSchedule->body_html
,
931 'source_contact_id' => $session->get('userID') ?
$session->get('userID') : $dao->contactID
,
932 'target_contact_id' => $dao->contactID
,
933 'activity_date_time' => date('YmdHis'),
934 'status_id' => $activityStatusID,
935 'activity_type_id' => $activityTypeID,
936 'source_record_id' => $dao->entityID
,
938 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
940 //file reminder on case if source activity is a case activity
941 if (!empty($dao->case_id
)) {
942 $caseActivityParams = array();
943 $caseActivityParams['case_id'] = $dao->case_id
;
944 $caseActivityParams['activity_id'] = $activity->id
;
945 CRM_Case_BAO_Case
::processCaseActivity($caseActivityParams);
955 * @param int $mappingID
957 * @param array $params
959 * @throws API_Exception
961 public static function buildRecipientContacts($mappingID, $now, $params = array()) {
962 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
963 $actionSchedule->mapping_id
= $mappingID;
964 $actionSchedule->is_active
= 1;
965 if (!empty($params)) {
966 _civicrm_api3_dao_set_filter($actionSchedule, $params, FALSE);
968 $actionSchedule->find();
970 while ($actionSchedule->fetch()) {
971 $mapping = new CRM_Core_DAO_ActionMapping();
972 $mapping->id
= $mappingID;
973 $mapping->find(TRUE);
975 // note: $where - this filtering applies for both
976 // 'limit to' and 'addition to' options
977 // $limitWhere - this filtering applies only for
979 $select = $join = $where = $limitWhere = array();
980 $selectColumns = "contact_id, entity_id, entity_table, action_schedule_id";
981 $limitTo = $actionSchedule->limit_to
;
982 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
983 trim($actionSchedule->entity_value
, CRM_Core_DAO
::VALUE_SEPARATOR
)
985 $value = implode(',', $value);
987 $status = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
988 trim($actionSchedule->entity_status
, CRM_Core_DAO
::VALUE_SEPARATOR
)
990 $status = implode(',', $status);
992 $anniversary = FALSE;
994 if (!CRM_Utils_System
::isNull($mapping->entity_recipient
)) {
995 if ($mapping->entity_recipient
== 'event_contacts') {
996 $recipientOptions = CRM_Core_OptionGroup
::values($mapping->entity_recipient
, FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
999 $recipientOptions = CRM_Core_OptionGroup
::values($mapping->entity_recipient
, FALSE, FALSE, FALSE, NULL, 'name');
1002 $from = "{$mapping->entity} e";
1004 if ($mapping->entity
== 'civicrm_activity') {
1005 $contactField = 'r.contact_id';
1006 $table = 'civicrm_activity e';
1007 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1008 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1009 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1010 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1012 if (!is_null($limitTo)) {
1013 if ($limitTo == 0) {
1014 // including the activity target contacts if 'in addition' is defined
1015 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
1018 switch (CRM_Utils_Array
::value($actionSchedule->recipient
, $recipientOptions)) {
1019 case 'Activity Assignees':
1020 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$assigneeID}";
1023 case 'Activity Source':
1024 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$sourceID}";
1028 case 'Activity Targets':
1029 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
1034 // build where clause
1035 if (!empty($value)) {
1036 $where[] = "e.activity_type_id IN ({$value})";
1039 $where[] = "e.activity_type_id IS NULL";
1041 if (!empty($status)) {
1042 $where[] = "e.status_id IN ({$status})";
1044 $where[] = ' e.is_current_revision = 1 ';
1045 $where[] = ' e.is_deleted = 0 ';
1047 $dateField = 'e.activity_date_time';
1050 if ($mapping->entity
== 'civicrm_participant') {
1051 $table = 'civicrm_event r';
1052 $contactField = 'e.contact_id';
1053 $join[] = 'INNER JOIN civicrm_event r ON e.event_id = r.id';
1054 if ($actionSchedule->recipient_listing
&& $limitTo) {
1055 $rList = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1056 trim($actionSchedule->recipient_listing
, CRM_Core_DAO
::VALUE_SEPARATOR
)
1058 $rList = implode(',', $rList);
1060 switch (CRM_Utils_Array
::value($actionSchedule->recipient
, $recipientOptions)) {
1061 case 'participant_role':
1062 $where[] = "e.role_id IN ({$rList})";
1070 // build where clause
1071 if (!empty($value)) {
1072 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IN ({$value})" : "r.id IN ({$value})";
1075 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IS NULL" : "r.id IS NULL";
1078 // participant status criteria not to be implemented
1079 // for additional recipients
1080 if (!empty($status)) {
1081 $limitWhere[] = "e.status_id IN ({$status})";
1084 $where[] = 'r.is_active = 1';
1085 $where[] = 'r.is_template = 0';
1086 $dateField = str_replace('event_', 'r.', $actionSchedule->start_action_date
);
1090 if ($mapping->entity
== 'civicrm_membership') {
1091 $contactField = 'e.contact_id';
1092 $table = 'civicrm_membership e';
1093 // build where clause
1095 //auto-renew memberships
1096 $where[] = "e.contribution_recur_id IS NOT NULL ";
1098 elseif ($status == 1) {
1099 $where[] = "e.contribution_recur_id IS NULL ";
1102 // build where clause
1103 if (!empty($value)) {
1104 $where[] = "e.membership_type_id IN ({$value})";
1107 $where[] = "e.membership_type_id IS NULL";
1110 $where[] = "( e.is_override IS NULL OR e.is_override = 0 )";
1111 $dateField = str_replace('membership_', 'e.', $actionSchedule->start_action_date
);
1112 $notINClause = self
::permissionedRelationships($contactField);
1114 $membershipStatus = CRM_Member_PseudoConstant
::membershipStatus(NULL, "(is_current_member = 1 OR name = 'Expired')", 'id');
1115 $mStatus = implode(',', $membershipStatus);
1116 $where[] = "e.status_id IN ({$mStatus})";
1118 // We are not tracking the reference date for 'repeated' schedule reminders,
1119 // for further details please check CRM-15376
1120 if ($actionSchedule->start_action_date
&& $actionSchedule->is_repeat
== FALSE) {
1121 $select[] = $dateField;
1122 $selectColumns = "reference_date, " . $selectColumns;
1126 if ($mapping->entity
== 'civicrm_contact') {
1127 $contactFields = array(
1132 if (in_array($value, $contactFields)) {
1133 $dateDBField = $value;
1134 $table = 'civicrm_contact e';
1135 $contactField = 'e.id';
1136 $where[] = 'e.is_deleted = 0';
1137 $where[] = 'e.is_deceased = 0';
1141 $customFieldParams = array('id' => substr($value, 7));
1142 $customGroup = $customField = array();
1143 CRM_Core_BAO_CustomField
::retrieve($customFieldParams, $customField);
1144 $dateDBField = $customField['column_name'];
1145 $customGroupParams = array('id' => $customField['custom_group_id'], $customGroup);
1146 CRM_Core_BAO_CustomGroup
::retrieve($customGroupParams, $customGroup);
1147 $from = $table = "{$customGroup['table_name']} e";
1148 $contactField = 'e.entity_id';
1149 $where[] = '1'; // possible to have no "where" in this case
1152 $status_ = explode(',', $status);
1153 if (in_array(2, $status_)) {
1154 // anniversary mode:
1155 $dateField = 'DATE_ADD(e.' . $dateDBField . ', INTERVAL ROUND(DATEDIFF(DATE(' . $now . '), e.' . $dateDBField . ') / 365) YEAR)';
1156 $anniversary = TRUE;
1160 $dateField = 'e.' . $dateDBField;
1164 // CRM-13577 Introduce Smart Groups Handling
1165 if ($actionSchedule->group_id
) {
1167 // Need to check if its a smart group or not
1168 // Then decide which table to join onto the query
1169 $group = CRM_Contact_DAO_Group
::getTableName();
1171 // Get the group information
1173 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
1175 WHERE $group.id = {$actionSchedule->group_id}
1178 $groupDAO = CRM_Core_DAO
::executeQuery($sql);
1179 $isSmartGroup = FALSE;
1181 $groupDAO->fetch() &&
1182 !empty($groupDAO->saved_search_id
)
1184 // Check that the group is in place in the cache and up to date
1185 CRM_Contact_BAO_GroupContactCache
::check($actionSchedule->group_id
);
1186 // Set smart group flag
1187 $isSmartGroup = TRUE;
1190 // CRM-13577 End Introduce Smart Groups Handling
1193 if ($actionSchedule->group_id
) {
1194 // CRM-13577 If smart group then use Cache table
1195 if ($isSmartGroup) {
1196 $join[] = "INNER JOIN civicrm_group_contact_cache grp ON {$contactField} = grp.contact_id";
1197 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1200 $join[] = "INNER JOIN civicrm_group_contact grp ON {$contactField} = grp.contact_id AND grp.status = 'Added'";
1201 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1204 elseif (!empty($actionSchedule->recipient_manual
)) {
1205 $rList = CRM_Utils_Type
::escape($actionSchedule->recipient_manual
, 'String');
1206 $where[] = "{$contactField} IN ({$rList})";
1209 elseif (!is_null($limitTo)) {
1210 $addGroup = $addWhere = '';
1211 if ($actionSchedule->group_id
) {
1212 // CRM-13577 If smart group then use Cache table
1213 if ($isSmartGroup) {
1214 $addGroup = " INNER JOIN civicrm_group_contact_cache grp ON c.id = grp.contact_id";
1215 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1218 $addGroup = " INNER JOIN civicrm_group_contact grp ON c.id = grp.contact_id AND grp.status = 'Added'";
1219 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1222 if (!empty($actionSchedule->recipient_manual
)) {
1223 $rList = CRM_Utils_Type
::escape($actionSchedule->recipient_manual
, 'String');
1224 $addWhere = "c.id IN ({$rList})";
1228 $select[] = "{$contactField} as contact_id";
1229 $select[] = 'e.id as entity_id';
1230 $select[] = "'{$mapping->entity}' as entity_table";
1231 $select[] = "{$actionSchedule->id} as action_schedule_id";
1232 $reminderJoinClause = "civicrm_action_log reminder ON reminder.contact_id = {$contactField} AND
1233 reminder.entity_id = e.id AND
1234 reminder.entity_table = '{$mapping->entity}' AND
1235 reminder.action_schedule_id = %1";
1238 // only consider reminders less than 11 months ago
1239 $reminderJoinClause .= " AND reminder.action_date_time > DATE_SUB({$now}, INTERVAL 11 MONTH)";
1242 if ($table != 'civicrm_contact e') {
1243 $join[] = "INNER JOIN civicrm_contact c ON c.id = {$contactField} AND c.is_deleted = 0 AND c.is_deceased = 0 ";
1246 $multilingual = CRM_Core_I18n
::isMultilingual();
1247 if ($multilingual && !empty($actionSchedule->filter_contact_language
)) {
1248 $tableAlias = ($table != 'civicrm_contact e') ?
'c' : 'e';
1250 // get language filter for the schedule
1251 $filter_contact_language = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $actionSchedule->filter_contact_language
);
1253 if (($key = array_search(CRM_Core_I18n
::NONE
, $filter_contact_language)) !== false) {
1254 $w .= "{$tableAlias}.preferred_language IS NULL OR {$tableAlias}.preferred_language = '' OR ";
1255 unset($filter_contact_language[$key]);
1257 if (count($filter_contact_language) > 0) {
1258 $w .= "{$tableAlias}.preferred_language IN ('" . implode("','", $filter_contact_language) . "')";
1263 if ($actionSchedule->start_action_date
) {
1264 $startDateClause = array();
1265 $op = ($actionSchedule->start_action_condition
== 'before' ?
'<=' : '>=');
1266 $operator = ($actionSchedule->start_action_condition
== 'before' ?
'DATE_SUB' : 'DATE_ADD');
1267 $date = $operator . "({$dateField}, INTERVAL {$actionSchedule->start_action_offset} {$actionSchedule->start_action_unit})";
1268 $startDateClause[] = "'{$now}' >= {$date}";
1269 if ($mapping->entity
== 'civicrm_participant') {
1270 $startDateClause[] = $operator . "({$now}, INTERVAL 1 DAY ) {$op} " . $dateField;
1273 $startDateClause[] = "DATE_SUB({$now}, INTERVAL 1 DAY ) <= {$date}";
1276 $startDate = implode(' AND ', $startDateClause);
1278 elseif ($actionSchedule->absolute_date
) {
1279 $startDate = "DATEDIFF(DATE('{$now}'),'{$actionSchedule->absolute_date}') = 0";
1282 // ( now >= date_built_from_start_time ) OR ( now = absolute_date )
1283 $dateClause = "reminder.id IS NULL AND {$startDate}";
1285 // start composing query
1286 $selectClause = 'SELECT ' . implode(', ', $select);
1287 $fromClause = "FROM $from";
1288 $joinClause = !empty($join) ?
implode(' ', $join) : '';
1289 $whereClause = 'WHERE ' . implode(' AND ', $where);
1290 $limitWhereClause = '';
1291 if (!empty($limitWhere)) {
1292 $limitWhereClause = ' AND ' . implode(' AND ', $limitWhere);
1296 INSERT INTO civicrm_action_log ({$selectColumns})
1300 LEFT JOIN {$reminderJoinClause}
1301 {$whereClause} {$limitWhereClause} AND {$dateClause} {$notINClause}
1304 // In some cases reference_date got outdated due to many reason e.g. In Membership renewal end_date got extended
1305 // which means reference date mismatches with the end_date where end_date may be used as the start_action_date
1306 // criteria for some schedule reminder so in order to send new reminder we INSERT new reminder with new reference_date
1307 // value via UNION operation
1308 if (strpos($selectColumns, 'reference_date') !== FALSE) {
1309 $dateClause = str_replace('reminder.id IS NULL', 'reminder.id IS NOT NULL', $dateClause);
1311 INSERT INTO civicrm_action_log ({$selectColumns})
1315 LEFT JOIN {$reminderJoinClause}
1316 {$whereClause} {$limitWhereClause} {$notINClause} AND {$dateClause} AND
1317 reminder.action_date_time IS NOT NULL AND
1318 reminder.reference_date IS NOT NULL
1319 GROUP BY reminder.id, reminder.reference_date
1320 HAVING reminder.id = MAX(reminder.id) AND reminder.reference_date <> {$dateField}
1324 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
1326 if (!empty($referenceQuery)) {
1327 CRM_Core_DAO
::executeQuery($referenceQuery, array(1 => array($actionSchedule->id
, 'Integer')));
1330 $isSendToAdditionalContacts = (!is_null($limitTo) && $limitTo == 0 && (!empty($addGroup) ||
!empty($addWhere))) ?
TRUE : FALSE;
1331 if ($isSendToAdditionalContacts) {
1332 $contactTable = "civicrm_contact c";
1333 $addSelect = "SELECT c.id as contact_id, c.id as entity_id, 'civicrm_contact' as entity_table, {$actionSchedule->id} as action_schedule_id";
1334 $additionReminderClause = "civicrm_action_log reminder ON reminder.contact_id = c.id AND
1335 reminder.entity_id = c.id AND
1336 reminder.entity_table = 'civicrm_contact' AND
1337 reminder.action_schedule_id = {$actionSchedule->id}";
1338 $addWhereClause = '';
1340 $addWhereClause = "AND {$addWhere}";
1342 $insertAdditionalSql = "
1343 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1345 FROM ({$contactTable})
1346 LEFT JOIN {$additionReminderClause}
1348 WHERE c.is_deleted = 0 AND c.is_deceased = 0
1351 AND reminder.id IS NULL
1353 SELECT rem.contact_id
1354 FROM civicrm_action_log rem INNER JOIN {$mapping->entity} e ON rem.entity_id = e.id
1355 WHERE rem.action_schedule_id = {$actionSchedule->id}
1356 AND rem.entity_table = '{$mapping->entity}'
1360 CRM_Core_DAO
::executeQuery($insertAdditionalSql);
1362 // if repeat is turned ON:
1363 if ($actionSchedule->is_repeat
) {
1364 $repeatEvent = ($actionSchedule->end_action
== 'before' ?
'DATE_SUB' : 'DATE_ADD') . "({$dateField}, INTERVAL {$actionSchedule->end_frequency_interval} {$actionSchedule->end_frequency_unit})";
1366 if ($actionSchedule->repetition_frequency_unit
== 'day') {
1367 $interval = "{$actionSchedule->repetition_frequency_interval} DAY";
1369 elseif ($actionSchedule->repetition_frequency_unit
== 'week') {
1370 $interval = "{$actionSchedule->repetition_frequency_interval} WEEK";
1372 elseif ($actionSchedule->repetition_frequency_unit
== 'month') {
1373 $interval = "{$actionSchedule->repetition_frequency_interval} MONTH";
1375 elseif ($actionSchedule->repetition_frequency_unit
== 'year') {
1376 $interval = "{$actionSchedule->repetition_frequency_interval} YEAR";
1379 $interval = "{$actionSchedule->repetition_frequency_interval} HOUR";
1382 // (now <= repeat_end_time )
1383 $repeatEventClause = "'{$now}' <= {$repeatEvent}";
1384 // diff(now && logged_date_time) >= repeat_interval
1385 $havingClause = "HAVING TIMESTAMPDIFF(HOUR, latest_log_time, CAST({$now} AS datetime)) >= TIMESTAMPDIFF(HOUR, latest_log_time, DATE_ADD(latest_log_time, INTERVAL $interval))";
1386 $groupByClause = 'GROUP BY reminder.contact_id, reminder.entity_id, reminder.entity_table';
1387 $selectClause .= ', MAX(reminder.action_date_time) as latest_log_time';
1388 //CRM-15376 - do not send our reminders if original criteria no longer applies
1389 // the first part of the startDateClause array is the earliest the reminder can be sent. If the
1390 // event (e.g membership_end_date) has changed then the reminder may no longer apply
1391 // @todo - this only handles events that get moved later. Potentially they might get moved earlier
1392 $originalEventStartDateClause = empty($startDateClause) ?
'' : 'AND' . $startDateClause[0];
1393 $sqlInsertValues = "{$selectClause}
1396 INNER JOIN {$reminderJoinClause}
1397 {$whereClause} {$limitWhereClause} AND {$repeatEventClause} {$originalEventStartDateClause} {$notINClause}
1401 $valsqlInsertValues = CRM_Core_DAO
::executeQuery($sqlInsertValues, array(
1403 $actionSchedule->id
,
1409 $arrValues = array();
1410 while ($valsqlInsertValues->fetch()) {
1411 $arrValues[] = "( {$valsqlInsertValues->contact_id}, {$valsqlInsertValues->entity_id}, '{$valsqlInsertValues->entity_table}',{$valsqlInsertValues->action_schedule_id} )";
1414 $valString = implode(',', $arrValues);
1418 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1419 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
1422 if ($isSendToAdditionalContacts) {
1423 $addSelect .= ', MAX(reminder.action_date_time) as latest_log_time';
1424 $sqlEndEventCheck = "
1425 SELECT * FROM {$table}
1426 {$whereClause} AND {$repeatEventClause} LIMIT 1";
1428 $daoCheck = CRM_Core_DAO
::executeQuery($sqlEndEventCheck);
1429 if ($daoCheck->fetch()) {
1430 $valSqlAdditionInsert = "
1432 FROM {$contactTable}
1434 INNER JOIN {$additionReminderClause}
1435 WHERE {$addWhere} AND c.is_deleted = 0 AND c.is_deceased = 0
1436 GROUP BY reminder.contact_id
1439 $daoForVals = CRM_Core_DAO
::executeQuery($valSqlAdditionInsert);
1440 $addValues = array();
1441 while ($daoForVals->fetch()) {
1442 $addValues[] = "( {$daoForVals->contact_id}, {$daoForVals->entity_id}, '{$daoForVals->entity_table}',{$daoForVals->action_schedule_id} )";
1444 $valString = implode(',', $addValues);
1448 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1449 CRM_Core_DAO
::executeQuery($query);
1460 * @return null|string
1462 public static function permissionedRelationships($field) {
1464 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
1465 FROM civicrm_membership m
1466 LEFT JOIN civicrm_membership cm ON cm.id = m.owner_membership_id
1467 LEFT JOIN civicrm_membership_type cmt ON cmt.id = m.membership_type_id
1468 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 )
1469 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 ) )
1470 WHERE m.owner_membership_id IS NOT NULL AND
1471 ( rel.is_permission_a_b = 0 OR rel.is_permission_b_a = 0)
1474 $excludeIds = array();
1475 $dao = CRM_Core_DAO
::executeQuery($query, array());
1476 while ($dao->fetch()) {
1477 if ($dao->slave_contact
== $dao->contact_id_a
&& $dao->is_permission_a_b
== 0) {
1478 $excludeIds[] = $dao->slave_contact
;
1480 elseif ($dao->slave_contact
== $dao->contact_id_b
&& $dao->is_permission_b_a
== 0) {
1481 $excludeIds[] = $dao->slave_contact
;
1485 if (!empty($excludeIds)) {
1486 $clause = "AND {$field} NOT IN ( " . implode(', ', $excludeIds) . ' ) ';
1494 * @param array $params
1498 public static function processQueue($now = NULL, $params = array()) {
1499 $now = $now ? CRM_Utils_Time
::setTime($now) : CRM_Utils_Time
::getTime();
1501 $mappings = self
::getMapping();
1502 foreach ($mappings as $mappingID => $mapping) {
1503 self
::buildRecipientContacts($mappingID, $now, $params);
1504 self
::sendMailings($mappingID, $now);
1509 'messages' => ts('Sent all scheduled reminders successfully'),
1516 * @param int $mappingID
1518 * @return null|string
1520 public static function isConfigured($id, $mappingID) {
1521 $queryString = "SELECT count(id) FROM civicrm_action_schedule
1522 WHERE mapping_id = %1 AND
1526 1 => array($mappingID, 'Integer'),
1527 2 => array($id, 'Integer'),
1529 return CRM_Core_DAO
::singleValueQuery($queryString, $params);
1533 * @param int $mappingID
1534 * @param $recipientType
1538 public static function getRecipientListing($mappingID, $recipientType) {
1540 if (!$mappingID ||
!$recipientType) {
1544 $mapping = self
::getMapping($mappingID);
1546 switch ($mapping['entity']) {
1547 case 'civicrm_participant':
1548 $eventContacts = CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
1549 if (empty($eventContacts[$recipientType])) {
1552 if ($eventContacts[$recipientType] == 'participant_role') {
1553 $options = CRM_Event_PseudoConstant
::participantRole();
1562 * @param $communication_language
1563 * @param $preferred_language
1565 public static function setCommunicationLanguage($communication_language, $preferred_language) {
1566 $config = CRM_Core_Config
::singleton();
1567 $language = $config->lcMessages
;
1569 // prepare the language for the email
1570 if ($communication_language == CRM_Core_I18n
::AUTO
) {
1571 if (!empty($preferred_language)) {
1572 $language = $preferred_language;
1576 $language = $communication_language;
1579 // language not in the existing language, use default
1580 $languages = CRM_Core_I18n
::languages(TRUE);
1581 if (!in_array($language, $languages)) {
1582 $language = $config->lcMessages
;
1585 // change the language
1586 $i18n = CRM_Core_I18n
::singleton();
1587 $i18n->setLanguage($language);