3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright (C) 2011 Marty Wright |
7 | Licensed to CiviCRM under the Academic Free License version 3.0. |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
32 * @copyright CiviCRM LLC (c) 2004-2014
38 * This class contains functions for managing Scheduled Reminders
40 class CRM_Core_BAO_ActionSchedule
extends CRM_Core_DAO_ActionSchedule
{
47 public static function getMapping($id = NULL) {
48 static $_action_mapping;
50 if ($id && !is_null($_action_mapping) && isset($_action_mapping[$id])) {
51 return $_action_mapping[$id];
54 $dao = new CRM_Core_DAO_ActionMapping();
61 while ($dao->fetch()) {
63 CRM_Core_DAO
::storeValues($dao, $defaults);
64 $mapping[$dao->id
] = $defaults;
66 $_action_mapping = $mapping;
72 * Get all fields of the type Date
75 public static function getDateFields() {
76 $allFields = CRM_Core_BAO_CustomField
::getFields('');
77 $dateFields = array('birth_date' => ts('Birth Date'));
78 foreach ($allFields as $fieldID => $field) {
79 if ($field['data_type'] == 'Date') {
80 $dateFields["custom_$fieldID"] = $field['label'];
87 * Retrieve list of selections/drop downs for Scheduled Reminder form
92 * @return array associated array of all the drop downs in the form
95 public static function getSelection($id = NULL) {
96 $mapping = self
::getMapping();
97 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
98 $activityType = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE);
100 $participantStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label');
101 $event = CRM_Event_PseudoConstant
::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
102 $eventType = CRM_Event_PseudoConstant
::eventType();
103 $eventTemplate = CRM_Event_PseudoConstant
::eventTemplates();
104 $autoRenew = CRM_Core_OptionGroup
::values('auto_renew_options');
105 $membershipType = CRM_Member_PseudoConstant
::membershipType();
106 $dateFieldParams = array('data_type' => 'Date');
107 $dateFields = self
::getDateFields();
108 $contactOptions = CRM_Core_OptionGroup
::values('contact_date_reminder_options');
110 asort($activityType);
112 $sel1 = $sel2 = $sel3 = $sel4 = $sel5 = array();
114 'manual' => ts('Choose Recipient(s)'),
115 'group' => ts('Select Group'),
118 $entityMapping = array();
119 $recipientMapping = array_combine(array_keys($options), array_keys($options));
125 foreach ($mapping as $value) {
126 $entityValue = CRM_Utils_Array
::value('entity_value', $value);
127 $entityStatus = CRM_Utils_Array
::value('entity_status', $value);
128 $entityRecipient = CRM_Utils_Array
::value('entity_recipient', $value);
129 $valueLabel = array('- ' . strtolower(CRM_Utils_Array
::value('entity_value_label', $value)) . ' -');
130 $key = CRM_Utils_Array
::value('id', $value);
131 $entityMapping[$key] = CRM_Utils_Array
::value('entity', $value);
134 switch ($entityValue) {
135 case 'activity_type':
136 if ($value['entity'] == 'civicrm_activity') {
137 $sel1Val = ts('Activity');
139 $sel2[$key] = $valueLabel +
$activityType;
143 if ($value['entity'] == 'civicrm_participant') {
144 $sel1Val = ts('Event Type');
146 $sel2[$key] = $valueLabel +
$eventType;
149 case 'event_template':
150 if ($value['entity'] == 'civicrm_participant') {
151 $sel1Val = ts('Event Template');
153 $sel2[$key] = $valueLabel +
$eventTemplate;
156 case 'civicrm_event':
157 if ($value['entity'] == 'civicrm_participant') {
158 $sel1Val = ts('Event Name');
160 $sel2[$key] = $valueLabel +
$event;
163 case 'civicrm_membership_type':
164 if ($value['entity'] == 'civicrm_membership') {
165 $sel1Val = ts('Membership');
167 $sel2[$key] = $valueLabel +
$membershipType;
170 case 'civicrm_contact':
171 if ($value['entity'] == 'civicrm_contact') {
172 $sel1Val = ts('Contact');
174 $sel2[$key] = $dateFields;
177 $sel1[$key] = $sel1Val;
180 if ($startDate = CRM_Utils_Array
::value('entity_date_start', $value)) {
181 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
183 if ($endDate = CRM_Utils_Array
::value('entity_date_end', $value)) {
184 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
187 switch ($entityRecipient) {
188 case 'activity_contacts':
189 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts');
190 $sel5[$entityRecipient] = $activityContacts +
$options;
191 $recipientMapping +
= CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
194 case 'event_contacts':
195 $eventContacts = CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name');
196 $sel5[$entityRecipient] = $eventContacts +
$options;
197 $recipientMapping +
= CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
201 $sel5[$entityRecipient] = $options;
208 foreach ($mapping as $value) {
209 $entityStatus = CRM_Utils_Array
::value('entity_status', $value);
210 $statusLabel = array('- ' . strtolower(CRM_Utils_Array
::value('entity_status_label', $value)) . ' -');
211 $id = CRM_Utils_Array
::value('id', $value);
213 switch ($entityStatus) {
214 case 'activity_status':
215 foreach ($sel3[$id] as $kkey => & $vval) {
216 $vval = $statusLabel +
$activityStatus;
220 case 'civicrm_participant_status_type':
221 foreach ($sel3[$id] as $kkey => & $vval) {
222 $vval = $statusLabel +
$participantStatus;
226 case 'auto_renew_options':
227 foreach ($sel3[$id] as $kkey => & $vval) {
230 $auto = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $kkey, 'auto_renew');
233 $vval = $statusLabel +
$autoRenew;
236 $vval = $statusLabel;
241 case 'contact_date_reminder_options':
242 foreach ($sel3[$id] as $kkey => & $vval) {
243 $vval = $contactOptions;
259 'entityMapping' => $entityMapping,
260 'recipientMapping' => $recipientMapping,
269 public static function getSelection1($id = NULL) {
270 $mapping = self
::getMapping($id);
271 $sel4 = $sel5 = array();
273 'manual' => ts('Choose Recipient(s)'),
274 'group' => ts('Select Group'),
277 $recipientMapping = array_combine(array_keys($options), array_keys($options));
279 foreach ($mapping as $value) {
280 $entityRecipient = CRM_Utils_Array
::value('entity_recipient', $value);
281 $key = CRM_Utils_Array
::value('id', $value);
283 if ($startDate = CRM_Utils_Array
::value('entity_date_start', $value)) {
284 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
286 if ($endDate = CRM_Utils_Array
::value('entity_date_end', $value)) {
287 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
290 switch ($entityRecipient) {
291 case 'activity_contacts':
292 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts');
293 $sel5[$id] = $activityContacts +
$options;
294 $recipientMapping +
= CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
297 case 'event_contacts':
298 $eventContacts = CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name');
299 $sel5[$id] = $eventContacts +
$options;
300 $recipientMapping +
= CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
304 $sel5[$id] = $options;
311 'sel5' => $sel5[$id],
312 'recipientMapping' => $recipientMapping,
317 * Retrieve list of Scheduled Reminders
319 * @param bool $namesOnly
320 * Return simple list of names.
322 * @param null $entityValue
325 * @return array (reference) reminder list
328 public static function &getList($namesOnly = FALSE, $entityValue = NULL, $id = NULL) {
329 $activity_type = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE);
330 $activity_status = CRM_Core_PseudoConstant
::activityStatus();
332 $event_type = CRM_Event_PseudoConstant
::eventType();
333 $civicrm_event = CRM_Event_PseudoConstant
::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
334 $civicrm_participant_status_type = CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label');
335 $event_template = CRM_Event_PseudoConstant
::eventTemplates();
336 $civicrm_contact = self
::getDateFields();
338 $auto_renew_options = CRM_Core_OptionGroup
::values('auto_renew_options');
339 $contact_date_reminder_options = CRM_Core_OptionGroup
::values('contact_date_reminder_options');
340 $civicrm_membership_type = CRM_Member_PseudoConstant
::membershipType();
343 'civicrm_activity' => 'Activity',
344 'civicrm_participant' => 'Event',
345 'civicrm_membership' => 'Member',
346 'civicrm_contact' => 'Contact',
354 cam.entity_value as entityValue,
355 cas.entity_value as entityValueIds,
356 cam.entity_status as entityStatus,
357 cas.entity_status as entityStatusIds,
358 cas.start_action_date as entityDate,
359 cas.start_action_offset,
360 cas.start_action_unit,
361 cas.start_action_condition,
366 FROM civicrm_action_schedule cas
367 LEFT JOIN civicrm_action_mapping cam ON (cam.id = cas.mapping_id)
369 $params = CRM_Core_DAO
::$_nullArray;
370 $where = " WHERE 1 ";
371 if ($entityValue and $id) {
373 AND cas.entity_value = $id AND
374 cam.entity_value = '$entityValue'";
377 1 => array($id, 'Integer'),
378 2 => array($entityValue, 'String'),
381 $where .= " AND cas.used_for IS NULL";
383 $dao = CRM_Core_DAO
::executeQuery($query);
384 while ($dao->fetch()) {
385 $list[$dao->id
]['id'] = $dao->id
;
386 $list[$dao->id
]['title'] = $dao->title
;
387 $list[$dao->id
]['start_action_offset'] = $dao->start_action_offset
;
388 $list[$dao->id
]['start_action_unit'] = $dao->start_action_unit
;
389 $list[$dao->id
]['start_action_condition'] = $dao->start_action_condition
;
390 $list[$dao->id
]['entityDate'] = ucwords(str_replace('_', ' ', $dao->entityDate
));
391 $list[$dao->id
]['absolute_date'] = $dao->absolute_date
;
393 $status = $dao->entityStatus
;
394 $statusArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityStatusIds
);
395 foreach ($statusArray as & $s) {
396 $s = CRM_Utils_Array
::value($s, $
$status);
398 $statusIds = implode(', ', $statusArray);
400 $value = $dao->entityValue
;
401 $valueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityValueIds
);
402 foreach ($valueArray as & $v) {
403 $v = CRM_Utils_Array
::value($v, $
$value);
405 $valueIds = implode(', ', $valueArray);
406 $list[$dao->id
]['entity'] = $entity[$dao->entity
];
407 $list[$dao->id
]['value'] = $valueIds;
408 $list[$dao->id
]['status'] = $statusIds;
409 $list[$dao->id
]['is_repeat'] = $dao->is_repeat
;
410 $list[$dao->id
]['is_active'] = $dao->is_active
;
417 * @param int $contactId
419 * @param int $scheduleID
421 * @param array $tokenParams
424 * @throws CRM_Core_Exception
426 public static function sendReminder($contactId, $to, $scheduleID, $from, $tokenParams) {
427 $email = $to['email'];
428 $phoneNumber = $to['phone'];
429 $schedule = new CRM_Core_DAO_ActionSchedule();
430 $schedule->id
= $scheduleID;
432 $domain = CRM_Core_BAO_Domain
::getDomain();
434 $hookTokens = array();
436 if ($schedule->find(TRUE)) {
437 $body_text = $schedule->body_text
;
438 $body_html = $schedule->body_html
;
439 $sms_body_text = $schedule->sms_body_text
;
440 $body_subject = $schedule->subject
;
442 $body_text = CRM_Utils_String
::htmlToText($body_html);
445 $params = array(array('contact_id', '=', $contactId, 0, 0));
446 list($contact, $_) = CRM_Contact_BAO_Query
::apiQuery($params);
449 $contact = reset($contact);
451 if (!$contact ||
is_a($contact, 'CRM_Core_Error')) {
455 // merge activity tokens with contact array
456 $contact = array_merge($contact, $tokenParams);
459 CRM_Utils_Hook
::tokenValues($contact, $contactId);
461 CRM_Utils_Hook
::tokens($hookTokens);
462 $categories = array_keys($hookTokens);
464 $type = array('body_html' => 'html', 'body_text' => 'text', 'sms_body_text' => 'text');
466 foreach ($type as $bodyType => $value) {
467 $dummy_mail = new CRM_Mailing_BAO_Mailing();
468 if ($bodyType == 'sms_body_text') {
469 $dummy_mail->body_text
= $
$bodyType;
472 $dummy_mail->$bodyType = $
$bodyType;
474 $tokens = $dummy_mail->getTokens();
477 CRM_Utils_Token
::replaceGreetingTokens($
$bodyType, NULL, $contact['contact_id']);
478 $
$bodyType = CRM_Utils_Token
::replaceDomainTokens($
$bodyType, $domain, TRUE, $tokens[$value], TRUE);
479 $
$bodyType = CRM_Utils_Token
::replaceContactTokens($
$bodyType, $contact, FALSE, $tokens[$value], FALSE, TRUE);
480 $
$bodyType = CRM_Utils_Token
::replaceComponentTokens($
$bodyType, $contact, $tokens[$value], TRUE, FALSE);
481 $
$bodyType = CRM_Utils_Token
::replaceHookTokens($
$bodyType, $contact, $categories, TRUE);
486 $sms_text = $sms_body_text;
488 $smarty = CRM_Core_Smarty
::singleton();
490 'text', 'html', 'sms_text') as $elem) {
491 $
$elem = $smarty->fetch("string:{$$elem}");
494 //@todo - this next section is a duplicate of function CRM_Utils_Token::getTokens
496 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
502 $subjectToken = NULL;
504 foreach ($matches[1] as $token) {
505 list($type, $name) = preg_split('/\./', $token, 2);
507 if (!isset($subjectToken[$type])) {
508 $subjectToken[$type] = array();
510 $subjectToken[$type][] = $name;
515 // @todo this (along with the copy-&-paste chunk above is a commonly repeated chunk of code & should be in a re-usable function
516 $messageSubject = CRM_Utils_Token
::replaceContactTokens($body_subject, $contact, FALSE, $subjectToken);
517 $messageSubject = CRM_Utils_Token
::replaceDomainTokens($messageSubject, $domain, TRUE, $subjectToken);
518 $messageSubject = CRM_Utils_Token
::replaceComponentTokens($messageSubject, $contact, $subjectToken, TRUE);
519 $messageSubject = CRM_Utils_Token
::replaceHookTokens($messageSubject, $contact, $categories, TRUE);
521 $messageSubject = $smarty->fetch("string:{$messageSubject}");
523 if ($schedule->mode
== 'SMS' or $schedule->mode
== 'User_Preference') {
524 $session = CRM_Core_Session
::singleton();
525 $userID = $session->get('userID') ?
$session->get('userID') : $contactId;
526 $smsParams = array('To' => $phoneNumber, 'provider_id' => $schedule->sms_provider_id
, 'activity_subject' => $messageSubject);
527 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
531 $activityParams = array(
532 'source_contact_id' => $userID,
533 'activity_type_id' => $activityTypeID,
534 'activity_date_time' => date('YmdHis'),
535 'subject' => $messageSubject,
536 'details' => $sms_text,
537 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
540 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
542 CRM_Activity_BAO_Activity
::sendSMSMessage($contactId,
550 if ($schedule->mode
== 'Email' or $schedule->mode
== 'User_Preference') {
551 // set up the parameters for CRM_Utils_Mail::send
553 'groupName' => 'Scheduled Reminder Sender',
555 'toName' => $contact['display_name'],
557 'subject' => $messageSubject,
558 'entity' => 'action_schedule',
559 'entity_id' => $scheduleID,
562 if (!$html ||
$contact['preferred_mail_format'] == 'Text' ||
563 $contact['preferred_mail_format'] == 'Both'
565 // render the & entities in text mode, so that the links work
566 $mailParams['text'] = str_replace('&', '&', $text);
568 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
569 $contact['preferred_mail_format'] == 'Both'
572 $mailParams['html'] = $html;
574 $result = CRM_Utils_Mail
::send($mailParams);
583 * Add the schedules reminders in the db
585 * @param array $params
586 * (reference ) an assoc array of name/value pairs.
588 * The array that holds all the db ids.
590 * @return CRM_Core_DAO_ActionSchedule
594 public static function add(&$params, $ids = array()) {
595 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
596 $actionSchedule->copyValues($params);
598 return $actionSchedule->save();
602 * Takes a bunch of params that are needed to match certain criteria and
603 * retrieves the relevant objects. It also stores all the retrieved
604 * values in the default array
606 * @param array $params
607 * (reference ) an assoc array of name/value pairs.
608 * @param array $values
609 * (reference ) an assoc array to hold the flattened values.
611 * @return CRM_Core_DAO_ActionSchedule object on success, null otherwise
614 public static function retrieve(&$params, &$values) {
615 if (empty($params)) {
618 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
620 $actionSchedule->copyValues($params);
622 if ($actionSchedule->find(TRUE)) {
623 $ids['actionSchedule'] = $actionSchedule->id
;
625 CRM_Core_DAO
::storeValues($actionSchedule, $values);
627 return $actionSchedule;
636 * ID of the Reminder to be deleted.
640 public static function del($id) {
642 $dao = new CRM_Core_DAO_ActionSchedule();
644 if ($dao->find(TRUE)) {
649 CRM_Core_Error
::fatal(ts('Invalid value passed to delete function.'));
653 * Update the is_active flag in the db
656 * Id of the database record.
657 * @param bool $is_active
658 * Value we want to set the is_active field.
660 * @return Object DAO object on success, null otherwise
663 public static function setIsActive($id, $is_active) {
664 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
668 * @param int $mappingID
671 * @throws CRM_Core_Exception
673 public static function sendMailings($mappingID, $now) {
674 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
675 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
677 $mapping = new CRM_Core_DAO_ActionMapping();
678 $mapping->id
= $mappingID;
679 $mapping->find(TRUE);
681 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
682 $actionSchedule->mapping_id
= $mappingID;
683 $actionSchedule->is_active
= 1;
684 $actionSchedule->find(FALSE);
686 $tokenFields = array();
687 $session = CRM_Core_Session
::singleton();
689 while ($actionSchedule->fetch()) {
690 $extraSelect = $extraJoin = $extraWhere = $extraOn = '';
692 if ($actionSchedule->from_email
) {
693 $fromEmailAddress = "$actionSchedule->from_name <$actionSchedule->from_email>";
696 $activityTypeID = FALSE;
697 $activityStatusID = FALSE;
698 if ($actionSchedule->record_activity
) {
699 if ($mapping->entity
== 'civicrm_membership') {
701 CRM_Core_OptionGroup
::getValue('activity_type', 'Membership Renewal Reminder', 'name');
705 CRM_Core_OptionGroup
::getValue('activity_type', 'Reminder Sent', 'name');
709 CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
712 if ($mapping->entity
== 'civicrm_activity') {
713 $compInfo = CRM_Core_Component
::getEnabledComponents();
714 $tokenEntity = 'activity';
715 $tokenFields = array('activity_id', 'activity_type', 'subject', 'details', 'activity_date_time');
716 $extraSelect = ', ov.label as activity_type, e.id as activity_id';
718 INNER JOIN civicrm_option_group og ON og.name = 'activity_type'
719 INNER JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
720 $extraOn = ' AND e.is_current_revision = 1 AND e.is_deleted = 0 ';
721 if ($actionSchedule->limit_to
== 0) {
723 LEFT JOIN civicrm_option_group og ON og.name = 'activity_type'
724 LEFT JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
728 // if CiviCase component is enabled
729 if (array_key_exists('CiviCase', $compInfo)) {
730 $extraSelect .= ", civicrm_case_activity.case_id as case_id";
732 LEFT JOIN `civicrm_case_activity` ON `e`.`id` = `civicrm_case_activity`.`activity_id`";
736 if ($mapping->entity
== 'civicrm_participant') {
737 $tokenEntity = 'event';
738 $tokenFields = array('event_type', 'title', 'event_id', 'start_date', 'end_date', 'summary', 'description', 'location', 'info_url', 'registration_url', 'fee_amount', 'contact_email', 'contact_phone', 'balance');
739 $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 ';
742 INNER JOIN civicrm_event ev ON e.event_id = ev.id
743 INNER JOIN civicrm_option_group og ON og.name = 'event_type'
744 INNER JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
745 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
746 LEFT JOIN civicrm_address address ON address.id = lb.address_id
747 LEFT JOIN civicrm_email email ON email.id = lb.email_id
748 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
750 if ($actionSchedule->limit_to
== 0) {
752 LEFT JOIN civicrm_event ev ON e.event_id = ev.id
753 LEFT JOIN civicrm_option_group og ON og.name = 'event_type'
754 LEFT JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
755 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
756 LEFT JOIN civicrm_address address ON address.id = lb.address_id
757 LEFT JOIN civicrm_email email ON email.id = lb.email_id
758 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
763 if ($mapping->entity
== 'civicrm_membership') {
764 $tokenEntity = 'membership';
765 $tokenFields = array('fee', 'id', 'join_date', 'start_date', 'end_date', 'status', 'type');
766 $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';
768 INNER JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
769 INNER JOIN civicrm_membership_status ms ON e.status_id = ms.id';
771 if ($actionSchedule->limit_to
== 0) {
773 LEFT JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
774 LEFT JOIN civicrm_membership_status ms ON e.status_id = ms.id';
778 if ($mapping->entity
== 'civicrm_contact') {
779 $tokenEntity = 'contact';
780 //TODO: get full list somewhere!
781 $tokenFields = array('birth_date', 'last_name');
782 //TODO: is there anything to add here?
785 $entityJoinClause = "INNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
786 if ($actionSchedule->limit_to
== 0) {
787 $entityJoinClause = "LEFT JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
788 $extraWhere .= " AND (e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact')";
790 $entityJoinClause .= $extraOn;
793 SELECT reminder.id as reminderID, reminder.contact_id as contactID, reminder.entity_table as entityTable, reminder.*, e.id as entityID, e.* {$extraSelect}
794 FROM civicrm_action_log reminder
797 WHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL
800 $dao = CRM_Core_DAO
::executeQuery($query,
801 array(1 => array($actionSchedule->id
, 'Integer'))
804 while ($dao->fetch()) {
805 $entityTokenParams = array();
806 foreach ($tokenFields as $field) {
807 if ($field == 'location') {
809 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
810 $loc['street_address'] = $dao->street_address
;
811 $loc['city'] = $dao->city
;
812 $loc['state_province'] = CRM_Utils_Array
::value($dao->state_province_id
, $stateProvince);
813 $loc['postal_code'] = $dao->postal_code
;
814 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address
::format($loc);
816 elseif ($field == 'info_url') {
817 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
819 elseif ($field == 'registration_url') {
820 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
822 elseif (in_array($field, array('start_date', 'end_date', 'join_date', 'activity_date_time'))) {
823 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date
::customFormat($dao->$field);
825 elseif ($field == 'balance') {
826 if ($dao->entityTable
== 'civicrm_contact') {
829 elseif (!empty($dao->entityID
)) {
830 $info = CRM_Contribute_BAO_Contribution
::getPaymentInfo($dao->entityID
, 'event');
831 $balancePay = CRM_Utils_Array
::value('balance', $info);
832 $balancePay = CRM_Utils_Money
::format($balancePay);
834 $entityTokenParams["{$tokenEntity}." . $field] = $balancePay;
836 elseif ($field == 'fee_amount') {
837 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Money
::format($dao->$field);
840 $entityTokenParams["{$tokenEntity}." . $field] = $dao->$field;
845 $errorMsg = $toEmail = $toPhoneNumber = '';
847 if ($actionSchedule->mode
== 'SMS' or $actionSchedule->mode
== 'User_Preference') {
848 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
849 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($dao->contactID
, FALSE, 'Mobile', $filters);
850 //to get primary mobile ph,if not get a first mobile phONE
851 if (!empty($toPhoneNumbers)) {
852 $toPhoneNumberDetails = reset($toPhoneNumbers);
853 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumberDetails);
854 //contact allows to send sms
858 if ($actionSchedule->mode
== 'Email' or $actionSchedule->mode
== 'User_Preference') {
859 $toEmail = CRM_Contact_BAO_Contact
::getPrimaryEmail($dao->contactID
);
861 if ($toEmail ||
!(empty($toPhoneNumber) or $toDoNotSms)) {
862 $to['email'] = $toEmail;
863 $to['phone'] = $toPhoneNumber;
865 CRM_Core_BAO_ActionSchedule
::sendReminder(
873 if (!$result ||
is_a($result, 'PEAR_Error')) {
874 // we could not send an email, for now we ignore, CRM-3406
880 $errorMsg = "Couldn\'t find recipient\'s email address.";
883 // update action log record
885 'id' => $dao->reminderID
,
886 'is_error' => $isError,
887 'message' => $errorMsg ?
$errorMsg : "null",
888 'action_date_time' => $now,
890 CRM_Core_BAO_ActionLog
::create($logParams);
892 // insert activity log record if needed
893 if ($actionSchedule->record_activity
&& !$isError) {
894 $activityParams = array(
895 'subject' => $actionSchedule->title
,
896 'details' => $actionSchedule->body_html
,
897 'source_contact_id' =>
898 $session->get('userID') ?
$session->get('userID') : $dao->contactID
,
899 'target_contact_id' => $dao->contactID
,
900 'activity_date_time' => date('YmdHis'),
901 'status_id' => $activityStatusID,
902 'activity_type_id' => $activityTypeID,
903 'source_record_id' => $dao->entityID
,
905 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
907 //file reminder on case if source activity is a case activity
908 if (!empty($dao->case_id
)) {
909 $caseActivityParams = array();
910 $caseActivityParams['case_id'] = $dao->case_id
;
911 $caseActivityParams['activity_id'] = $activity->id
;
912 CRM_Case_BAO_Case
::processCaseActivity($caseActivityParams);
922 * @param int $mappingID
924 * @param array $params
926 * @throws API_Exception
928 public static function buildRecipientContacts($mappingID, $now, $params = array()) {
929 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
930 $actionSchedule->mapping_id
= $mappingID;
931 $actionSchedule->is_active
= 1;
932 if (!empty($params)) {
933 _civicrm_api3_dao_set_filter($actionSchedule, $params, FALSE, 'ActionSchedule');
935 $actionSchedule->find();
937 while ($actionSchedule->fetch()) {
938 $mapping = new CRM_Core_DAO_ActionMapping();
939 $mapping->id
= $mappingID;
940 $mapping->find(TRUE);
942 // note: $where - this filtering applies for both
943 // 'limit to' and 'addition to' options
944 // $limitWhere - this filtering applies only for
946 $select = $join = $where = $limitWhere = array();
947 $limitTo = $actionSchedule->limit_to
;
948 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
949 trim($actionSchedule->entity_value
, CRM_Core_DAO
::VALUE_SEPARATOR
)
951 $value = implode(',', $value);
953 $status = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
954 trim($actionSchedule->entity_status
, CRM_Core_DAO
::VALUE_SEPARATOR
)
956 $status = implode(',', $status);
958 $anniversary = FALSE;
960 if (!CRM_Utils_System
::isNull($mapping->entity_recipient
)) {
961 if ($mapping->entity_recipient
== 'event_contacts') {
962 $recipientOptions = CRM_Core_OptionGroup
::values($mapping->entity_recipient
, FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
965 $recipientOptions = CRM_Core_OptionGroup
::values($mapping->entity_recipient
, FALSE, FALSE, FALSE, NULL, 'name');
968 $from = "{$mapping->entity} e";
970 if ($mapping->entity
== 'civicrm_activity') {
971 $contactField = 'r.contact_id';
972 $table = 'civicrm_activity e';
973 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
974 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
975 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
976 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
978 if (!is_null($limitTo)) {
980 // including the activity target contacts if 'in addition' is defined
981 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
984 switch (CRM_Utils_Array
::value($actionSchedule->recipient
, $recipientOptions)) {
985 case 'Activity Assignees':
986 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$assigneeID}";
989 case 'Activity Source':
990 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$sourceID}";
994 case 'Activity Targets':
995 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
1000 // build where clause
1001 if (!empty($value)) {
1002 $where[] = "e.activity_type_id IN ({$value})";
1005 $where[] = "e.activity_type_id IS NULL";
1007 if (!empty($status)) {
1008 $where[] = "e.status_id IN ({$status})";
1010 $where[] = ' e.is_current_revision = 1 ';
1011 $where[] = ' e.is_deleted = 0 ';
1013 $dateField = 'e.activity_date_time';
1016 if ($mapping->entity
== 'civicrm_participant') {
1017 $table = 'civicrm_event r';
1018 $contactField = 'e.contact_id';
1019 $join[] = 'INNER JOIN civicrm_event r ON e.event_id = r.id';
1020 if ($actionSchedule->recipient_listing
&& $limitTo) {
1021 $rList = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1022 trim($actionSchedule->recipient_listing
, CRM_Core_DAO
::VALUE_SEPARATOR
)
1024 $rList = implode(',', $rList);
1026 switch ($recipientOptions[$actionSchedule->recipient
]) {
1027 case 'participant_role':
1028 $where[] = "e.role_id IN ({$rList})";
1036 // build where clause
1037 if (!empty($value)) {
1038 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IN ({$value})" : "r.id IN ({$value})";
1041 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IS NULL" : "r.id IS NULL";
1044 // participant status criteria not to be implemented
1045 // for additional recipients
1046 if (!empty($status)) {
1047 $limitWhere[] = "e.status_id IN ({$status})";
1050 $where[] = 'r.is_active = 1';
1051 $where[] = 'r.is_template = 0';
1052 $dateField = str_replace('event_', 'r.', $actionSchedule->start_action_date
);
1056 if ($mapping->entity
== 'civicrm_membership') {
1057 $contactField = 'e.contact_id';
1058 $table = 'civicrm_membership e';
1059 // build where clause
1061 //auto-renew memberships
1062 $where[] = "e.contribution_recur_id IS NOT NULL ";
1064 elseif ($status == 1) {
1065 $where[] = "e.contribution_recur_id IS NULL ";
1068 // build where clause
1069 if (!empty($value)) {
1070 $where[] = "e.membership_type_id IN ({$value})";
1073 $where[] = "e.membership_type_id IS NULL";
1076 $where[] = "( e.is_override IS NULL OR e.is_override = 0 )";
1077 $dateField = str_replace('membership_', 'e.', $actionSchedule->start_action_date
);
1078 $notINClause = self
::permissionedRelationships($contactField);
1080 $membershipStatus = CRM_Member_PseudoConstant
::membershipStatus(NULL, "(is_current_member = 1 OR name = 'Expired')", 'id');
1081 $mStatus = implode(',', $membershipStatus);
1082 $where[] = "e.status_id IN ({$mStatus})";
1085 if ($mapping->entity
== 'civicrm_contact') {
1086 if ($value == 'birth_date') {
1087 $dateDBField = 'birth_date';
1088 $table = 'civicrm_contact e';
1089 $contactField = 'e.id';
1090 $where[] = 'e.is_deleted = 0';
1091 $where[] = 'e.is_deceased = 0';
1095 $customFieldParams = array('id' => substr($value, 7));
1096 $customGroup = $customField = array();
1097 CRM_Core_BAO_CustomField
::retrieve($customFieldParams, $customField);
1098 $dateDBField = $customField['column_name'];
1099 $customGroupParams = array('id' => $customField['custom_group_id'], $customGroup);
1100 CRM_Core_BAO_CustomGroup
::retrieve($customGroupParams, $customGroup);
1101 $from = $table = "{$customGroup['table_name']} e";
1102 $contactField = 'e.entity_id';
1103 $where[] = '1'; // possible to have no "where" in this case
1106 $status_ = explode(',', $status);
1107 if (in_array(2, $status_)) {
1108 // anniversary mode:
1109 $dateField = 'DATE_ADD(e.' . $dateDBField . ', INTERVAL ROUND(DATEDIFF(DATE(' . $now . '), e.' . $dateDBField . ') / 365) YEAR)';
1110 $anniversary = TRUE;
1114 $dateField = 'e.' . $dateDBField;
1116 // TODO get this working
1118 // TODO: Make sure everything's provided for repetition, etc.
1121 // CRM-13577 Introduce Smart Groups Handling
1122 if ($actionSchedule->group_id
) {
1124 // Need to check if its a smart group or not
1125 // Then decide which table to join onto the query
1126 $group = CRM_Contact_DAO_Group
::getTableName();
1128 // Get the group information
1130 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
1132 WHERE $group.id = {$actionSchedule->group_id}
1135 $groupDAO = CRM_Core_DAO
::executeQuery($sql);
1136 $isSmartGroup = FALSE;
1138 $groupDAO->fetch() &&
1139 !empty($groupDAO->saved_search_id
)
1141 // Check that the group is in place in the cache and up to date
1142 CRM_Contact_BAO_GroupContactCache
::check($actionSchedule->group_id
);
1143 // Set smart group flag
1144 $isSmartGroup = TRUE;
1147 // CRM-13577 End Introduce Smart Groups Handling
1150 if ($actionSchedule->group_id
) {
1151 // CRM-13577 If smart group then use Cache table
1152 if ($isSmartGroup) {
1153 $join[] = "INNER JOIN civicrm_group_contact_cache grp ON {$contactField} = grp.contact_id";
1154 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1157 $join[] = "INNER JOIN civicrm_group_contact grp ON {$contactField} = grp.contact_id AND grp.status = 'Added'";
1158 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1161 elseif (!empty($actionSchedule->recipient_manual
)) {
1162 $rList = CRM_Utils_Type
::escape($actionSchedule->recipient_manual
, 'String');
1163 $where[] = "{$contactField} IN ({$rList})";
1166 elseif (!is_null($limitTo)) {
1167 $addGroup = $addWhere = '';
1168 if ($actionSchedule->group_id
) {
1169 // CRM-13577 If smart group then use Cache table
1170 if ($isSmartGroup) {
1171 $addGroup = " INNER JOIN civicrm_group_contact_cache grp ON c.id = grp.contact_id";
1172 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1175 $addGroup = " INNER JOIN civicrm_group_contact grp ON c.id = grp.contact_id AND grp.status = 'Added'";
1176 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1179 if (!empty($actionSchedule->recipient_manual
)) {
1180 $rList = CRM_Utils_Type
::escape($actionSchedule->recipient_manual
, 'String');
1181 $addWhere = "c.id IN ({$rList})";
1185 $select[] = "{$contactField} as contact_id";
1186 $select[] = 'e.id as entity_id';
1187 $select[] = "'{$mapping->entity}' as entity_table";
1188 $select[] = "{$actionSchedule->id} as action_schedule_id";
1189 $reminderJoinClause = "civicrm_action_log reminder ON reminder.contact_id = {$contactField} AND
1190 reminder.entity_id = e.id AND
1191 reminder.entity_table = '{$mapping->entity}' AND
1192 reminder.action_schedule_id = %1";
1195 // only consider reminders less than 11 months ago
1196 $reminderJoinClause .= " AND reminder.action_date_time > DATE_SUB({$now}, INTERVAL 11 MONTH)";
1199 if ($table != 'civicrm_contact e') {
1200 $join[] = "INNER JOIN civicrm_contact c ON c.id = {$contactField} AND c.is_deleted = 0 AND c.is_deceased = 0 ";
1203 if ($actionSchedule->start_action_date
) {
1204 $startDateClause = array();
1205 $op = ($actionSchedule->start_action_condition
== 'before' ?
'<=' : '>=');
1206 $operator = ($actionSchedule->start_action_condition
== 'before' ?
'DATE_SUB' : 'DATE_ADD');
1207 $date = $operator . "({$dateField}, INTERVAL {$actionSchedule->start_action_offset} {$actionSchedule->start_action_unit})";
1208 $startDateClause[] = "'{$now}' >= {$date}";
1209 if ($mapping->entity
== 'civicrm_participant') {
1210 $startDateClause[] = $operator . "({$now}, INTERVAL 1 DAY ) {$op} " . $dateField;
1213 $startDateClause[] = "DATE_SUB({$now}, INTERVAL 1 DAY ) <= {$date}";
1216 $startDate = implode(' AND ', $startDateClause);
1218 elseif ($actionSchedule->absolute_date
) {
1219 $startDate = "DATEDIFF(DATE('{$now}'),'{$actionSchedule->absolute_date}') = 0";
1222 // ( now >= date_built_from_start_time ) OR ( now = absolute_date )
1223 $dateClause = "reminder.id IS NULL AND {$startDate}";
1225 // start composing query
1226 $selectClause = 'SELECT ' . implode(', ', $select);
1227 $fromClause = "FROM $from";
1228 $joinClause = !empty($join) ?
implode(' ', $join) : '';
1229 $whereClause = 'WHERE ' . implode(' AND ', $where);
1230 $limitWhereClause = '';
1231 if (!empty($limitWhere)) {
1232 $limitWhereClause = ' AND ' . implode(' AND ', $limitWhere);
1236 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1240 LEFT JOIN {$reminderJoinClause}
1241 {$whereClause} {$limitWhereClause} AND {$dateClause} {$notINClause}
1243 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
1244 $isSendToAdditionalContacts = (!is_null($limitTo) && $limitTo == 0 && (!empty($addGroup) ||
!empty($addWhere))) ?
TRUE : FALSE;
1245 if ($isSendToAdditionalContacts) {
1246 $contactTable = "civicrm_contact c";
1247 $addSelect = "SELECT c.id as contact_id, c.id as entity_id, 'civicrm_contact' as entity_table, {$actionSchedule->id} as action_schedule_id";
1248 $additionReminderClause = "civicrm_action_log reminder ON reminder.contact_id = c.id AND
1249 reminder.entity_id = c.id AND
1250 reminder.entity_table = 'civicrm_contact' AND
1251 reminder.action_schedule_id = {$actionSchedule->id}";
1252 $addWhereClause = '';
1254 $addWhereClause = "AND {$addWhere}";
1256 $insertAdditionalSql = "
1257 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1259 FROM ({$contactTable})
1260 LEFT JOIN {$additionReminderClause}
1262 WHERE c.is_deleted = 0 AND c.is_deceased = 0
1266 SELECT rem.contact_id
1267 FROM civicrm_action_log rem INNER JOIN {$mapping->entity} e ON rem.entity_id = e.id
1268 WHERE rem.action_schedule_id = {$actionSchedule->id}
1269 AND rem.entity_table = '{$mapping->entity}'
1273 CRM_Core_DAO
::executeQuery($insertAdditionalSql);
1275 // if repeat is turned ON:
1276 if ($actionSchedule->is_repeat
) {
1277 $repeatEvent = ($actionSchedule->end_action
== 'before' ?
'DATE_SUB' : 'DATE_ADD') . "({$dateField}, INTERVAL {$actionSchedule->end_frequency_interval} {$actionSchedule->end_frequency_unit})";
1279 if ($actionSchedule->repetition_frequency_unit
== 'day') {
1280 $hrs = 24 * $actionSchedule->repetition_frequency_interval
;
1282 elseif ($actionSchedule->repetition_frequency_unit
== 'week') {
1283 $hrs = 24 * $actionSchedule->repetition_frequency_interval
* 7;
1285 elseif ($actionSchedule->repetition_frequency_unit
== 'month') {
1286 $hrs = "24*(DATEDIFF(DATE_ADD(latest_log_time, INTERVAL 1 MONTH ), latest_log_time))";
1288 elseif ($actionSchedule->repetition_frequency_unit
== 'year') {
1289 $hrs = "24*(DATEDIFF(DATE_ADD(latest_log_time, INTERVAL 1 YEAR ), latest_log_time))";
1292 $hrs = $actionSchedule->repetition_frequency_interval
;
1295 // (now <= repeat_end_time )
1296 $repeatEventClause = "'{$now}' <= {$repeatEvent}";
1297 // diff(now && logged_date_time) >= repeat_interval
1298 $havingClause = "HAVING TIMEDIFF({$now}, latest_log_time) >= TIME('{$hrs}:00:00')";
1299 $groupByClause = 'GROUP BY reminder.contact_id, reminder.entity_id, reminder.entity_table';
1300 $selectClause .= ', MAX(reminder.action_date_time) as latest_log_time';
1301 //CRM-15376 - do not send our reminders if original criteria no longer applies
1302 // the first part of the startDateClause array is the earliest the reminder can be sent. If the
1303 // event (e.g membership_end_date) has changed then the reminder may no longer apply
1304 // @todo - this only handles events that get moved later. Potentially they might get moved earlier
1305 $originalEventStartDateClause = empty($startDateClause) ?
'' : 'AND' . $startDateClause[0];
1306 $sqlInsertValues = "{$selectClause}
1309 INNER JOIN {$reminderJoinClause}
1310 {$whereClause} {$limitWhereClause} AND {$repeatEventClause} {$originalEventStartDateClause} {$notINClause}
1314 $valsqlInsertValues = CRM_Core_DAO
::executeQuery($sqlInsertValues, array(1 => array($actionSchedule->id
, 'Integer')));
1316 $arrValues = array();
1317 while ($valsqlInsertValues->fetch()) {
1318 $arrValues[] = "( {$valsqlInsertValues->contact_id}, {$valsqlInsertValues->entity_id}, '{$valsqlInsertValues->entity_table}',{$valsqlInsertValues->action_schedule_id} )";
1321 $valString = implode(',', $arrValues);
1325 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1326 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
1329 if ($isSendToAdditionalContacts) {
1330 $addSelect .= ', MAX(reminder.action_date_time) as latest_log_time';
1331 $sqlEndEventCheck = "
1332 SELECT * FROM {$table}
1333 {$whereClause} AND {$repeatEventClause} LIMIT 1";
1335 $daoCheck = CRM_Core_DAO
::executeQuery($sqlEndEventCheck);
1336 if ($daoCheck->fetch()) {
1337 $valSqlAdditionInsert = "
1339 FROM {$contactTable}
1341 INNER JOIN {$additionReminderClause}
1342 WHERE {$addWhere} AND c.is_deleted = 0 AND c.is_deceased = 0
1343 GROUP BY reminder.contact_id
1346 $daoForVals = CRM_Core_DAO
::executeQuery($valSqlAdditionInsert);
1347 $addValues = array();
1348 while ($daoForVals->fetch()) {
1349 $addValues[] = "( {$daoForVals->contact_id}, {$daoForVals->entity_id}, '{$daoForVals->entity_table}',{$daoForVals->action_schedule_id} )";
1351 $valString = implode(',', $addValues);
1355 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1356 CRM_Core_DAO
::executeQuery($query);
1367 * @return null|string
1369 public static function permissionedRelationships($field) {
1371 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
1372 FROM civicrm_membership m
1373 LEFT JOIN civicrm_membership cm ON cm.id = m.owner_membership_id
1374 LEFT JOIN civicrm_membership_type cmt ON cmt.id = m.membership_type_id
1375 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 )
1376 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 ) )
1377 WHERE m.owner_membership_id IS NOT NULL AND
1378 ( rel.is_permission_a_b = 0 OR rel.is_permission_b_a = 0)
1381 $excludeIds = array();
1382 $dao = CRM_Core_DAO
::executeQuery($query, array());
1383 while ($dao->fetch()) {
1384 if ($dao->slave_contact
== $dao->contact_id_a
&& $dao->is_permission_a_b
== 0) {
1385 $excludeIds[] = $dao->slave_contact
;
1387 elseif ($dao->slave_contact
== $dao->contact_id_b
&& $dao->is_permission_b_a
== 0) {
1388 $excludeIds[] = $dao->slave_contact
;
1392 if (!empty($excludeIds)) {
1393 $clause = "AND {$field} NOT IN ( " . implode(', ', $excludeIds) . ' ) ';
1401 * @param array $params
1405 public static function processQueue($now = NULL, $params = array()) {
1406 $now = $now ? CRM_Utils_Time
::setTime($now) : CRM_Utils_Time
::getTime();
1408 $mappings = self
::getMapping();
1409 foreach ($mappings as $mappingID => $mapping) {
1410 self
::buildRecipientContacts($mappingID, $now, $params);
1411 self
::sendMailings($mappingID, $now);
1416 'messages' => ts('Sent all scheduled reminders successfully'),
1423 * @param int $mappingID
1425 * @return null|string
1427 public static function isConfigured($id, $mappingID) {
1428 $queryString = "SELECT count(id) FROM civicrm_action_schedule
1429 WHERE mapping_id = %1 AND
1433 1 => array($mappingID, 'Integer'),
1434 2 => array($id, 'Integer'),
1436 return CRM_Core_DAO
::singleValueQuery($queryString, $params);
1440 * @param int $mappingID
1441 * @param $recipientType
1445 public static function getRecipientListing($mappingID, $recipientType) {
1447 if (!$mappingID ||
!$recipientType) {
1451 $mapping = self
::getMapping($mappingID);
1453 switch ($mapping['entity']) {
1454 case 'civicrm_participant':
1455 $eventContacts = CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
1456 if (empty($eventContacts[$recipientType])) {
1459 if ($eventContacts[$recipientType] == 'participant_role') {
1460 $options = CRM_Event_PseudoConstant
::participantRole();