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
89 * @param bool $id mapping id
91 * @return array associated array of all the drop downs in the form
94 public static function getSelection($id = NULL) {
95 $mapping = self
::getMapping();
96 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
97 $activityType = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE);
99 $participantStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label');
100 $event = CRM_Event_PseudoConstant
::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
101 $eventType = CRM_Event_PseudoConstant
::eventType();
102 $eventTemplate = CRM_Event_PseudoConstant
::eventTemplates();
103 $autoRenew = CRM_Core_OptionGroup
::values('auto_renew_options');
104 $membershipType = CRM_Member_PseudoConstant
::membershipType();
105 $dateFieldParams = array('data_type' => 'Date');
106 $dateFields = self
::getDateFields();
107 $contactOptions = CRM_Core_OptionGroup
::values('contact_date_reminder_options');
109 asort($activityType);
111 $sel1 = $sel2 = $sel3 = $sel4 = $sel5 = array();
113 'manual' => ts('Choose Recipient(s)'),
114 'group' => ts('Select Group'),
117 $entityMapping = array();
118 $recipientMapping = array_combine(array_keys($options), array_keys($options));
124 foreach ($mapping as $value) {
125 $entityValue = CRM_Utils_Array
::value('entity_value', $value);
126 $entityStatus = CRM_Utils_Array
::value('entity_status', $value);
127 $entityRecipient = CRM_Utils_Array
::value('entity_recipient', $value);
128 $valueLabel = array('- ' . strtolower(CRM_Utils_Array
::value('entity_value_label', $value)) . ' -');
129 $key = CRM_Utils_Array
::value('id', $value);
130 $entityMapping[$key] = CRM_Utils_Array
::value('entity', $value);
133 switch ($entityValue) {
134 case 'activity_type':
135 if ($value['entity'] == 'civicrm_activity') {
136 $sel1Val = ts('Activity');
138 $sel2[$key] = $valueLabel +
$activityType;
142 if ($value['entity'] == 'civicrm_participant') {
143 $sel1Val = ts('Event Type');
145 $sel2[$key] = $valueLabel +
$eventType;
148 case 'event_template':
149 if ($value['entity'] == 'civicrm_participant') {
150 $sel1Val = ts('Event Template');
152 $sel2[$key] = $valueLabel +
$eventTemplate;
155 case 'civicrm_event':
156 if ($value['entity'] == 'civicrm_participant') {
157 $sel1Val = ts('Event Name');
159 $sel2[$key] = $valueLabel +
$event;
162 case 'civicrm_membership_type':
163 if ($value['entity'] == 'civicrm_membership') {
164 $sel1Val = ts('Membership');
166 $sel2[$key] = $valueLabel +
$membershipType;
169 case 'civicrm_contact':
170 if ($value['entity'] == 'civicrm_contact') {
171 $sel1Val = ts('Contact');
173 $sel2[$key] = $dateFields;
176 $sel1[$key] = $sel1Val;
179 if ($startDate = CRM_Utils_Array
::value('entity_date_start', $value)) {
180 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
182 if ($endDate = CRM_Utils_Array
::value('entity_date_end', $value)) {
183 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
186 switch ($entityRecipient) {
187 case 'activity_contacts':
188 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts');
189 $sel5[$entityRecipient] = $activityContacts +
$options;
190 $recipientMapping +
= CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
193 case 'event_contacts':
194 $eventContacts = CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name');
195 $sel5[$entityRecipient] = $eventContacts +
$options;
196 $recipientMapping +
= CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
200 $sel5[$entityRecipient] = $options;
207 foreach ($mapping as $value) {
208 $entityStatus = CRM_Utils_Array
::value('entity_status', $value);
209 $statusLabel = array('- ' . strtolower(CRM_Utils_Array
::value('entity_status_label', $value)) . ' -');
210 $id = CRM_Utils_Array
::value('id', $value);
212 switch ($entityStatus) {
213 case 'activity_status':
214 foreach ($sel3[$id] as $kkey => & $vval) {
215 $vval = $statusLabel +
$activityStatus;
219 case 'civicrm_participant_status_type':
220 foreach ($sel3[$id] as $kkey => & $vval) {
221 $vval = $statusLabel +
$participantStatus;
225 case 'auto_renew_options':
226 foreach ($sel3[$id] as $kkey => & $vval) {
229 $auto = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $kkey, 'auto_renew');
232 $vval = $statusLabel +
$autoRenew;
235 $vval = $statusLabel;
240 case 'contact_date_reminder_options':
241 foreach ($sel3[$id] as $kkey => & $vval) {
242 $vval = $contactOptions;
258 'entityMapping' => $entityMapping,
259 'recipientMapping' => $recipientMapping,
268 public static function getSelection1($id = NULL) {
269 $mapping = self
::getMapping($id);
270 $sel4 = $sel5 = array();
272 'manual' => ts('Choose Recipient(s)'),
273 'group' => ts('Select Group'),
276 $recipientMapping = array_combine(array_keys($options), array_keys($options));
278 foreach ($mapping as $value) {
279 $entityRecipient = CRM_Utils_Array
::value('entity_recipient', $value);
280 $key = CRM_Utils_Array
::value('id', $value);
282 if ($startDate = CRM_Utils_Array
::value('entity_date_start', $value)) {
283 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
285 if ($endDate = CRM_Utils_Array
::value('entity_date_end', $value)) {
286 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
289 switch ($entityRecipient) {
290 case 'activity_contacts':
291 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts');
292 $sel5[$id] = $activityContacts +
$options;
293 $recipientMapping +
= CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
296 case 'event_contacts':
297 $eventContacts = CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name');
298 $sel5[$id] = $eventContacts +
$options;
299 $recipientMapping +
= CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
303 $sel5[$id] = $options;
310 'sel5' => $sel5[$id],
311 'recipientMapping' => $recipientMapping,
316 * Retrieve list of Scheduled Reminders
318 * @param bool $namesOnly return simple list of names
320 * @param null $entityValue
323 * @return array (reference) reminder list
326 public static function &getList($namesOnly = FALSE, $entityValue = NULL, $id = NULL) {
327 $activity_type = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE);
328 $activity_status = CRM_Core_PseudoConstant
::activityStatus();
330 $event_type = CRM_Event_PseudoConstant
::eventType();
331 $civicrm_event = CRM_Event_PseudoConstant
::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
332 $civicrm_participant_status_type = CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label');
333 $event_template = CRM_Event_PseudoConstant
::eventTemplates();
334 $civicrm_contact = self
::getDateFields();
336 $auto_renew_options = CRM_Core_OptionGroup
::values('auto_renew_options');
337 $contact_date_reminder_options = CRM_Core_OptionGroup
::values('contact_date_reminder_options');
338 $civicrm_membership_type = CRM_Member_PseudoConstant
::membershipType();
341 'civicrm_activity' => 'Activity',
342 'civicrm_participant' => 'Event',
343 'civicrm_membership' => 'Member',
344 'civicrm_contact' => 'Contact',
352 cam.entity_value as entityValue,
353 cas.entity_value as entityValueIds,
354 cam.entity_status as entityStatus,
355 cas.entity_status as entityStatusIds,
356 cas.start_action_date as entityDate,
357 cas.start_action_offset,
358 cas.start_action_unit,
359 cas.start_action_condition,
364 FROM civicrm_action_schedule cas
365 LEFT JOIN civicrm_action_mapping cam ON (cam.id = cas.mapping_id)
367 $params = CRM_Core_DAO
::$_nullArray;
368 $where = " WHERE 1 ";
369 if ($entityValue and $id) {
371 AND cas.entity_value = $id AND
372 cam.entity_value = '$entityValue'";
375 1 => array($id, 'Integer'),
376 2 => array($entityValue, 'String'),
379 $where .= " AND cas.used_for IS NULL";
381 $dao = CRM_Core_DAO
::executeQuery($query);
382 while ($dao->fetch()) {
383 $list[$dao->id
]['id'] = $dao->id
;
384 $list[$dao->id
]['title'] = $dao->title
;
385 $list[$dao->id
]['start_action_offset'] = $dao->start_action_offset
;
386 $list[$dao->id
]['start_action_unit'] = $dao->start_action_unit
;
387 $list[$dao->id
]['start_action_condition'] = $dao->start_action_condition
;
388 $list[$dao->id
]['entityDate'] = ucwords(str_replace('_', ' ', $dao->entityDate
));
389 $list[$dao->id
]['absolute_date'] = $dao->absolute_date
;
391 $status = $dao->entityStatus
;
392 $statusArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityStatusIds
);
393 foreach ($statusArray as & $s) {
394 $s = CRM_Utils_Array
::value($s, $
$status);
396 $statusIds = implode(', ', $statusArray);
398 $value = $dao->entityValue
;
399 $valueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityValueIds
);
400 foreach ($valueArray as & $v) {
401 $v = CRM_Utils_Array
::value($v, $
$value);
403 $valueIds = implode(', ', $valueArray);
404 $list[$dao->id
]['entity'] = $entity[$dao->entity
];
405 $list[$dao->id
]['value'] = $valueIds;
406 $list[$dao->id
]['status'] = $statusIds;
407 $list[$dao->id
]['is_repeat'] = $dao->is_repeat
;
408 $list[$dao->id
]['is_active'] = $dao->is_active
;
415 * @param int $contactId
417 * @param int $scheduleID
419 * @param array $tokenParams
422 * @throws CRM_Core_Exception
424 public static function sendReminder($contactId, $to, $scheduleID, $from, $tokenParams) {
425 $email = $to['email'];
426 $phoneNumber = $to['phone'];
427 $schedule = new CRM_Core_DAO_ActionSchedule();
428 $schedule->id
= $scheduleID;
430 $domain = CRM_Core_BAO_Domain
::getDomain();
432 $hookTokens = array();
434 if ($schedule->find(TRUE)) {
435 $body_text = $schedule->body_text
;
436 $body_html = $schedule->body_html
;
437 $sms_body_text = $schedule->sms_body_text
;
438 $body_subject = $schedule->subject
;
440 $body_text = CRM_Utils_String
::htmlToText($body_html);
443 $params = array(array('contact_id', '=', $contactId, 0, 0));
444 list($contact, $_) = CRM_Contact_BAO_Query
::apiQuery($params);
447 $contact = reset($contact);
449 if (!$contact ||
is_a($contact, 'CRM_Core_Error')) {
453 // merge activity tokens with contact array
454 $contact = array_merge($contact, $tokenParams);
457 CRM_Utils_Hook
::tokenValues($contact, $contactId);
459 CRM_Utils_Hook
::tokens($hookTokens);
460 $categories = array_keys($hookTokens);
462 $type = array('body_html' => 'html', 'body_text' => 'text', 'sms_body_text' => 'text');
464 foreach ($type as $bodyType => $value) {
465 $dummy_mail = new CRM_Mailing_BAO_Mailing();
466 if ($bodyType == 'sms_body_text') {
467 $dummy_mail->body_text
= $
$bodyType;
470 $dummy_mail->$bodyType = $
$bodyType;
472 $tokens = $dummy_mail->getTokens();
475 CRM_Utils_Token
::replaceGreetingTokens($
$bodyType, NULL, $contact['contact_id']);
476 $
$bodyType = CRM_Utils_Token
::replaceDomainTokens($
$bodyType, $domain, TRUE, $tokens[$value], TRUE);
477 $
$bodyType = CRM_Utils_Token
::replaceContactTokens($
$bodyType, $contact, FALSE, $tokens[$value], FALSE, TRUE);
478 $
$bodyType = CRM_Utils_Token
::replaceComponentTokens($
$bodyType, $contact, $tokens[$value], TRUE, FALSE);
479 $
$bodyType = CRM_Utils_Token
::replaceHookTokens($
$bodyType, $contact, $categories, TRUE);
484 $sms_text = $sms_body_text;
486 $smarty = CRM_Core_Smarty
::singleton();
488 'text', 'html', 'sms_text') as $elem) {
489 $
$elem = $smarty->fetch("string:{$$elem}");
493 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
499 $subjectToken = NULL;
501 foreach ($matches[1] as $token) {
502 list($type, $name) = preg_split('/\./', $token, 2);
504 if (!isset($subjectToken[$type])) {
505 $subjectToken[$type] = array();
507 $subjectToken[$type][] = $name;
512 $messageSubject = CRM_Utils_Token
::replaceContactTokens($body_subject, $contact, FALSE, $subjectToken);
513 $messageSubject = CRM_Utils_Token
::replaceDomainTokens($messageSubject, $domain, TRUE, $subjectToken);
514 $messageSubject = CRM_Utils_Token
::replaceComponentTokens($messageSubject, $contact, $subjectToken, TRUE);
515 $messageSubject = CRM_Utils_Token
::replaceHookTokens($messageSubject, $contact, $categories, TRUE);
517 $messageSubject = $smarty->fetch("string:{$messageSubject}");
519 if ($schedule->mode
== 'SMS' or $schedule->mode
== 'User_Preference') {
520 $session = CRM_Core_Session
::singleton();
521 $userID = $session->get('userID') ?
$session->get('userID') : $contactId;
522 $smsParams = array('To' => $phoneNumber, 'provider_id' => $schedule->sms_provider_id
, 'activity_subject' => $messageSubject);
523 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
527 $activityParams = array(
528 'source_contact_id' => $userID,
529 'activity_type_id' => $activityTypeID,
530 'activity_date_time' => date('YmdHis'),
531 'subject' => $messageSubject,
532 'details' => $sms_text,
533 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
536 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
538 CRM_Activity_BAO_Activity
::sendSMSMessage($contactId,
546 if ($schedule->mode
== 'Email' or $schedule->mode
== 'User_Preference') {
547 // set up the parameters for CRM_Utils_Mail::send
549 'groupName' => 'Scheduled Reminder Sender',
551 'toName' => $contact['display_name'],
553 'subject' => $messageSubject,
554 'entity' => 'action_schedule',
555 'entity_id' => $scheduleID,
558 if (!$html ||
$contact['preferred_mail_format'] == 'Text' ||
559 $contact['preferred_mail_format'] == 'Both'
561 // render the & entities in text mode, so that the links work
562 $mailParams['text'] = str_replace('&', '&', $text);
564 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
565 $contact['preferred_mail_format'] == 'Both'
568 $mailParams['html'] = $html;
570 $result = CRM_Utils_Mail
::send($mailParams);
579 * Add the schedules reminders in the db
581 * @param array $params (reference ) an assoc array of name/value pairs
582 * @param array $ids the array that holds all the db ids
584 * @return CRM_Core_DAO_ActionSchedule
588 public static function add(&$params, $ids = array()) {
589 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
590 $actionSchedule->copyValues($params);
592 return $actionSchedule->save();
596 * Takes a bunch of params that are needed to match certain criteria and
597 * retrieves the relevant objects. It also stores all the retrieved
598 * values in the default array
600 * @param array $params (reference ) an assoc array of name/value pairs
601 * @param array $values (reference ) an assoc array to hold the flattened values
603 * @return CRM_Core_DAO_ActionSchedule object on success, null otherwise
606 public static function retrieve(&$params, &$values) {
607 if (empty($params)) {
610 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
612 $actionSchedule->copyValues($params);
614 if ($actionSchedule->find(TRUE)) {
615 $ids['actionSchedule'] = $actionSchedule->id
;
617 CRM_Core_DAO
::storeValues($actionSchedule, $values);
619 return $actionSchedule;
627 * @param int $id ID of the Reminder to be deleted.
631 public static function del($id) {
633 $dao = new CRM_Core_DAO_ActionSchedule();
635 if ($dao->find(TRUE)) {
640 CRM_Core_Error
::fatal(ts('Invalid value passed to delete function.'));
644 * Update the is_active flag in the db
646 * @param int $id id of the database record
647 * @param boolean $is_active value we want to set the is_active field
649 * @return Object DAO object on success, null otherwise
652 public static function setIsActive($id, $is_active) {
653 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
657 * @param int $mappingID
660 * @throws CRM_Core_Exception
662 public static function sendMailings($mappingID, $now) {
663 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
664 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
666 $mapping = new CRM_Core_DAO_ActionMapping();
667 $mapping->id
= $mappingID;
668 $mapping->find(TRUE);
670 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
671 $actionSchedule->mapping_id
= $mappingID;
672 $actionSchedule->is_active
= 1;
673 $actionSchedule->find(FALSE);
675 $tokenFields = array();
676 $session = CRM_Core_Session
::singleton();
678 while ($actionSchedule->fetch()) {
679 $extraSelect = $extraJoin = $extraWhere = $extraOn = '';
681 if ($actionSchedule->from_email
)
682 $fromEmailAddress = "$actionSchedule->from_name <$actionSchedule->from_email>";
684 $activityTypeID = false;
685 $activityStatusID = false;
686 if ($actionSchedule->record_activity
) {
687 if ($mapping->entity
== 'civicrm_membership') {
689 CRM_Core_OptionGroup
::getValue('activity_type', 'Membership Renewal Reminder', 'name');
693 CRM_Core_OptionGroup
::getValue('activity_type', 'Reminder Sent', 'name');
697 CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
700 if ($mapping->entity
== 'civicrm_activity') {
701 $compInfo = CRM_Core_Component
::getEnabledComponents();
702 $tokenEntity = 'activity';
703 $tokenFields = array('activity_id', 'activity_type', 'subject', 'details', 'activity_date_time');
704 $extraSelect = ', ov.label as activity_type, e.id as activity_id';
706 INNER JOIN civicrm_option_group og ON og.name = 'activity_type'
707 INNER JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
708 $extraOn = ' AND e.is_current_revision = 1 AND e.is_deleted = 0 ';
709 if ($actionSchedule->limit_to
== 0) {
711 LEFT JOIN civicrm_option_group og ON og.name = 'activity_type'
712 LEFT JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
716 // if CiviCase component is enabled
717 if (array_key_exists('CiviCase', $compInfo)) {
718 $extraSelect .= ", civicrm_case_activity.case_id as case_id";
720 LEFT JOIN `civicrm_case_activity` ON `e`.`id` = `civicrm_case_activity`.`activity_id`";
724 if ($mapping->entity
== 'civicrm_participant') {
725 $tokenEntity = 'event';
726 $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');
727 $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 ';
730 INNER JOIN civicrm_event ev ON e.event_id = ev.id
731 INNER JOIN civicrm_option_group og ON og.name = 'event_type'
732 INNER JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
733 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
734 LEFT JOIN civicrm_address address ON address.id = lb.address_id
735 LEFT JOIN civicrm_email email ON email.id = lb.email_id
736 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
738 if ($actionSchedule->limit_to
== 0) {
740 LEFT JOIN civicrm_event ev ON e.event_id = ev.id
741 LEFT JOIN civicrm_option_group og ON og.name = 'event_type'
742 LEFT JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
743 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
744 LEFT JOIN civicrm_address address ON address.id = lb.address_id
745 LEFT JOIN civicrm_email email ON email.id = lb.email_id
746 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
751 if ($mapping->entity
== 'civicrm_membership') {
752 $tokenEntity = 'membership';
753 $tokenFields = array('fee', 'id', 'join_date', 'start_date', 'end_date', 'status', 'type');
754 $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';
756 INNER JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
757 INNER JOIN civicrm_membership_status ms ON e.status_id = ms.id';
759 if ($actionSchedule->limit_to
== 0) {
761 LEFT JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
762 LEFT JOIN civicrm_membership_status ms ON e.status_id = ms.id';
766 if ($mapping->entity
== 'civicrm_contact') {
767 $tokenEntity = 'contact';
768 //TODO: get full list somewhere!
769 $tokenFields = array('birth_date', 'last_name');
770 //TODO: is there anything to add here?
773 $entityJoinClause = "INNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
774 if ($actionSchedule->limit_to
== 0) {
775 $entityJoinClause = "LEFT JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
776 $extraWhere .= " AND (e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact')";
778 $entityJoinClause .= $extraOn;
781 SELECT reminder.id as reminderID, reminder.contact_id as contactID, reminder.entity_table as entityTable, reminder.*, e.id as entityID, e.* {$extraSelect}
782 FROM civicrm_action_log reminder
785 WHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL
788 $dao = CRM_Core_DAO
::executeQuery($query,
789 array(1 => array($actionSchedule->id
, 'Integer'))
792 while ($dao->fetch()) {
793 $entityTokenParams = array();
794 foreach ($tokenFields as $field) {
795 if ($field == 'location') {
797 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
798 $loc['street_address'] = $dao->street_address
;
799 $loc['city'] = $dao->city
;
800 $loc['state_province'] = CRM_Utils_Array
::value($dao->state_province_id
, $stateProvince);
801 $loc['postal_code'] = $dao->postal_code
;
802 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address
::format($loc);
804 elseif ($field == 'info_url') {
805 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
807 elseif ($field == 'registration_url') {
808 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
810 elseif (in_array($field, array('start_date','end_date','join_date','activity_date_time'))) {
811 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date
::customFormat($dao->$field);
813 elseif ($field == 'balance') {
814 if ($dao->entityTable
== 'civicrm_contact') {
817 elseif (!empty($dao->entityID
)) {
818 $info = CRM_Contribute_BAO_Contribution
::getPaymentInfo($dao->entityID
, 'event');
819 $balancePay = CRM_Utils_Array
::value('balance', $info);
820 $balancePay = CRM_Utils_Money
::format($balancePay);
822 $entityTokenParams["{$tokenEntity}." . $field] = $balancePay;
824 elseif ($field == 'fee_amount') {
825 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Money
::format($dao->$field);
828 $entityTokenParams["{$tokenEntity}." . $field] = $dao->$field;
833 $errorMsg = $toEmail = $toPhoneNumber = '';
835 if ($actionSchedule->mode
== 'SMS' or $actionSchedule->mode
== 'User_Preference') {
836 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
837 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($dao->contactID
, FALSE, 'Mobile', $filters);
838 //to get primary mobile ph,if not get a first mobile phONE
839 if (!empty($toPhoneNumbers)) {
840 $toPhoneNumberDetails = reset($toPhoneNumbers);
841 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumberDetails);
842 //contact allows to send sms
846 if ($actionSchedule->mode
== 'Email' or $actionSchedule->mode
== 'User_Preference') {
847 $toEmail = CRM_Contact_BAO_Contact
::getPrimaryEmail($dao->contactID
);
849 if ($toEmail ||
!(empty($toPhoneNumber) or $toDoNotSms)) {
850 $to['email'] = $toEmail;
851 $to['phone'] = $toPhoneNumber;
853 CRM_Core_BAO_ActionSchedule
::sendReminder(
861 if (!$result ||
is_a($result, 'PEAR_Error')) {
862 // we could not send an email, for now we ignore, CRM-3406
868 $errorMsg = "Couldn\'t find recipient\'s email address.";
871 // update action log record
873 'id' => $dao->reminderID
,
874 'is_error' => $isError,
875 'message' => $errorMsg ?
$errorMsg : "null",
876 'action_date_time' => $now,
878 CRM_Core_BAO_ActionLog
::create($logParams);
880 // insert activity log record if needed
881 if ($actionSchedule->record_activity
&& !$isError) {
882 $activityParams = array(
883 'subject' => $actionSchedule->title
,
884 'details' => $actionSchedule->body_html
,
885 'source_contact_id' =>
886 $session->get('userID') ?
$session->get('userID') : $dao->contactID
,
887 'target_contact_id' => $dao->contactID
,
888 'activity_date_time' => date('YmdHis'),
889 'status_id' => $activityStatusID,
890 'activity_type_id' => $activityTypeID,
891 'source_record_id' => $dao->entityID
,
893 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
895 //file reminder on case if source activity is a case activity
896 if (!empty($dao->case_id
)) {
897 $caseActivityParams = array();
898 $caseActivityParams['case_id'] = $dao->case_id
;
899 $caseActivityParams['activity_id'] = $activity->id
;
900 CRM_Case_BAO_Case
::processCaseActivity($caseActivityParams);
910 * @param int $mappingID
912 * @param array $params
914 * @throws API_Exception
916 public static function buildRecipientContacts($mappingID, $now, $params = array()) {
917 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
918 $actionSchedule->mapping_id
= $mappingID;
919 $actionSchedule->is_active
= 1;
920 if(!empty($params)) {
921 _civicrm_api3_dao_set_filter($actionSchedule, $params, FALSE, 'ActionSchedule');
923 $actionSchedule->find();
925 while ($actionSchedule->fetch()) {
926 $mapping = new CRM_Core_DAO_ActionMapping();
927 $mapping->id
= $mappingID;
928 $mapping->find(TRUE);
930 // note: $where - this filtering applies for both
931 // 'limit to' and 'addition to' options
932 // $limitWhere - this filtering applies only for
934 $select = $join = $where = $limitWhere = array();
935 $limitTo = $actionSchedule->limit_to
;
936 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
937 trim($actionSchedule->entity_value
, CRM_Core_DAO
::VALUE_SEPARATOR
)
939 $value = implode(',', $value);
941 $status = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
942 trim($actionSchedule->entity_status
, CRM_Core_DAO
::VALUE_SEPARATOR
)
944 $status = implode(',', $status);
946 $anniversary = false;
948 if (!CRM_Utils_System
::isNull($mapping->entity_recipient
)) {
949 if ($mapping->entity_recipient
== 'event_contacts') {
950 $recipientOptions = CRM_Core_OptionGroup
::values($mapping->entity_recipient
, FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
953 $recipientOptions = CRM_Core_OptionGroup
::values($mapping->entity_recipient
, FALSE, FALSE, FALSE, NULL, 'name');
956 $from = "{$mapping->entity} e";
958 if ($mapping->entity
== 'civicrm_activity') {
959 $contactField = 'r.contact_id';
960 $table = 'civicrm_activity e';
961 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
962 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
963 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
964 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
966 if (!is_null($limitTo)) {
968 // including the activity target contacts if 'in addition' is defined
969 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
972 switch (CRM_Utils_Array
::value($actionSchedule->recipient
, $recipientOptions)) {
973 case 'Activity Assignees':
974 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$assigneeID}";
977 case 'Activity Source':
978 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$sourceID}";
982 case 'Activity Targets':
983 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
988 // build where clause
989 if (!empty($value)) {
990 $where[] = "e.activity_type_id IN ({$value})";
993 $where[] = "e.activity_type_id IS NULL";
995 if (!empty($status)) {
996 $where[] = "e.status_id IN ({$status})";
998 $where[] = ' e.is_current_revision = 1 ';
999 $where[] = ' e.is_deleted = 0 ';
1001 $dateField = 'e.activity_date_time';
1004 if ($mapping->entity
== 'civicrm_participant') {
1005 $table = 'civicrm_event r';
1006 $contactField = 'e.contact_id';
1007 $join[] = 'INNER JOIN civicrm_event r ON e.event_id = r.id';
1008 if ($actionSchedule->recipient_listing
&& $limitTo) {
1009 $rList = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1010 trim($actionSchedule->recipient_listing
, CRM_Core_DAO
::VALUE_SEPARATOR
)
1012 $rList = implode(',', $rList);
1014 switch ($recipientOptions[$actionSchedule->recipient
]) {
1015 case 'participant_role':
1016 $where[] = "e.role_id IN ({$rList})";
1024 // build where clause
1025 if (!empty($value)) {
1026 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IN ({$value})" : "r.id IN ({$value})";
1029 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IS NULL" : "r.id IS NULL";
1032 // participant status criteria not to be implemented
1033 // for additional recipients
1034 if (!empty($status)) {
1035 $limitWhere[] = "e.status_id IN ({$status})";
1038 $where[] = 'r.is_active = 1';
1039 $where[] = 'r.is_template = 0';
1040 $dateField = str_replace('event_', 'r.', $actionSchedule->start_action_date
);
1044 if ($mapping->entity
== 'civicrm_membership') {
1045 $contactField = 'e.contact_id';
1046 $table = 'civicrm_membership e';
1047 // build where clause
1048 if ( $status == 2 ) {
1049 //auto-renew memberships
1050 $where[] = "e.contribution_recur_id IS NOT NULL ";
1052 elseif ( $status == 1 ) {
1053 $where[] = "e.contribution_recur_id IS NULL ";
1056 // build where clause
1057 if (!empty($value)) {
1058 $where[] = "e.membership_type_id IN ({$value})";
1061 $where[] = "e.membership_type_id IS NULL";
1064 $where[] = "( e.is_override IS NULL OR e.is_override = 0 )";
1065 $dateField = str_replace('membership_', 'e.', $actionSchedule->start_action_date
);
1066 $notINClause = self
::permissionedRelationships($contactField);
1068 $membershipStatus = CRM_Member_PseudoConstant
::membershipStatus(NULL, "(is_current_member = 1 OR name = 'Expired')", 'id');
1069 $mStatus = implode (',', $membershipStatus);
1070 $where[] = "e.status_id IN ({$mStatus})";
1073 if ($mapping->entity
== 'civicrm_contact') {
1074 if ($value == 'birth_date') {
1075 $dateDBField = 'birth_date';
1076 $table = 'civicrm_contact e';
1077 $contactField = 'e.id';
1078 $where[] = 'e.is_deleted = 0';
1079 $where[] = 'e.is_deceased = 0';
1083 $customFieldParams = array('id' => substr($value, 7));
1084 $customGroup = $customField = array();
1085 CRM_Core_BAO_CustomField
::retrieve($customFieldParams, $customField);
1086 $dateDBField = $customField['column_name'];
1087 $customGroupParams = array('id' => $customField['custom_group_id'], $customGroup);
1088 CRM_Core_BAO_CustomGroup
::retrieve($customGroupParams, $customGroup);
1089 $from = $table = "{$customGroup['table_name']} e";
1090 $contactField = 'e.entity_id';
1091 $where[] = '1'; // possible to have no "where" in this case
1094 $status_ = explode(',', $status);
1095 if (in_array(2, $status_)) {
1096 // anniversary mode:
1097 $dateField = 'DATE_ADD(e.' . $dateDBField . ', INTERVAL ROUND(DATEDIFF(DATE(' . $now . '), e.' . $dateDBField . ') / 365) YEAR)';
1098 $anniversary = true;
1102 $dateField = 'e.' . $dateDBField;
1104 // TODO get this working
1106 // TODO: Make sure everything's provided for repetition, etc.
1109 // CRM-13577 Introduce Smart Groups Handling
1110 if ($actionSchedule->group_id
) {
1112 // Need to check if its a smart group or not
1113 // Then decide which table to join onto the query
1114 $group = CRM_Contact_DAO_Group
::getTableName();
1116 // Get the group information
1118 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
1120 WHERE $group.id = {$actionSchedule->group_id}
1123 $groupDAO = CRM_Core_DAO
::executeQuery($sql);
1124 $isSmartGroup = FALSE;
1126 $groupDAO->fetch() &&
1127 !empty($groupDAO->saved_search_id
)
1129 // Check that the group is in place in the cache and up to date
1130 CRM_Contact_BAO_GroupContactCache
::check($actionSchedule->group_id
);
1131 // Set smart group flag
1132 $isSmartGroup = TRUE;
1135 // CRM-13577 End Introduce Smart Groups Handling
1138 if ($actionSchedule->group_id
) {
1139 // CRM-13577 If smart group then use Cache table
1140 if ($isSmartGroup) {
1141 $join[] = "INNER JOIN civicrm_group_contact_cache grp ON {$contactField} = grp.contact_id";
1142 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1144 $join[] = "INNER JOIN civicrm_group_contact grp ON {$contactField} = grp.contact_id AND grp.status = 'Added'";
1145 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1148 elseif (!empty($actionSchedule->recipient_manual
)) {
1149 $rList = CRM_Utils_Type
::escape($actionSchedule->recipient_manual
, 'String');
1150 $where[] = "{$contactField} IN ({$rList})";
1153 elseif (!is_null($limitTo)) {
1154 $addGroup = $addWhere = '';
1155 if ($actionSchedule->group_id
) {
1156 // CRM-13577 If smart group then use Cache table
1157 if ($isSmartGroup) {
1158 $addGroup = " INNER JOIN civicrm_group_contact_cache grp ON c.id = grp.contact_id";
1159 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1161 $addGroup = " INNER JOIN civicrm_group_contact grp ON c.id = grp.contact_id AND grp.status = 'Added'";
1162 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1165 if (!empty($actionSchedule->recipient_manual
)) {
1166 $rList = CRM_Utils_Type
::escape($actionSchedule->recipient_manual
, 'String');
1167 $addWhere = "c.id IN ({$rList})";
1171 $select[] = "{$contactField} as contact_id";
1172 $select[] = 'e.id as entity_id';
1173 $select[] = "'{$mapping->entity}' as entity_table";
1174 $select[] = "{$actionSchedule->id} as action_schedule_id";
1175 $reminderJoinClause = "civicrm_action_log reminder ON reminder.contact_id = {$contactField} AND
1176 reminder.entity_id = e.id AND
1177 reminder.entity_table = '{$mapping->entity}' AND
1178 reminder.action_schedule_id = %1";
1181 // only consider reminders less than 11 months ago
1182 $reminderJoinClause .= " AND reminder.action_date_time > DATE_SUB({$now}, INTERVAL 11 MONTH)";
1185 if ($table != 'civicrm_contact e') {
1186 $join[] = "INNER JOIN civicrm_contact c ON c.id = {$contactField} AND c.is_deleted = 0 AND c.is_deceased = 0 ";
1189 if ($actionSchedule->start_action_date
) {
1190 $startDateClause = array();
1191 $op = ($actionSchedule->start_action_condition
== 'before' ?
'<=' : '>=');
1192 $operator = ($actionSchedule->start_action_condition
== 'before' ?
'DATE_SUB' : 'DATE_ADD');
1193 $date = $operator . "({$dateField}, INTERVAL {$actionSchedule->start_action_offset} {$actionSchedule->start_action_unit})";
1194 $startDateClause[] = "'{$now}' >= {$date}";
1195 if ($mapping->entity
== 'civicrm_participant') {
1196 $startDateClause[] = $operator. "({$now}, INTERVAL 1 DAY ) {$op} " . $dateField;
1199 $startDateClause[] = "DATE_SUB({$now}, INTERVAL 1 DAY ) <= {$date}";
1202 $startDate = implode(' AND ', $startDateClause);
1204 elseif ($actionSchedule->absolute_date
) {
1205 $startDate = "DATEDIFF(DATE('{$now}'),'{$actionSchedule->absolute_date}') = 0";
1208 // ( now >= date_built_from_start_time ) OR ( now = absolute_date )
1209 $dateClause = "reminder.id IS NULL AND {$startDate}";
1211 // start composing query
1212 $selectClause = 'SELECT ' . implode(', ', $select);
1213 $fromClause = "FROM $from";
1214 $joinClause = !empty($join) ?
implode(' ', $join) : '';
1215 $whereClause = 'WHERE ' . implode(' AND ', $where);
1216 $limitWhereClause = '';
1217 if (!empty($limitWhere)) {
1218 $limitWhereClause = ' AND ' . implode(' AND ', $limitWhere);
1222 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1226 LEFT JOIN {$reminderJoinClause}
1227 {$whereClause} {$limitWhereClause} AND {$dateClause} {$notINClause}
1229 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
1230 $isSendToAdditionalContacts = (!is_null($limitTo) && $limitTo == 0 && (!empty($addGroup) ||
!empty($addWhere))) ?
TRUE : FALSE;
1231 if ($isSendToAdditionalContacts) {
1232 $contactTable = "civicrm_contact c";
1233 $addSelect = "SELECT c.id as contact_id, c.id as entity_id, 'civicrm_contact' as entity_table, {$actionSchedule->id} as action_schedule_id";
1234 $additionReminderClause = "civicrm_action_log reminder ON reminder.contact_id = c.id AND
1235 reminder.entity_id = c.id AND
1236 reminder.entity_table = 'civicrm_contact' AND
1237 reminder.action_schedule_id = {$actionSchedule->id}";
1238 $addWhereClause = '';
1240 $addWhereClause = "AND {$addWhere}";
1242 $insertAdditionalSql ="
1243 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1245 FROM ({$contactTable})
1246 LEFT JOIN {$additionReminderClause}
1248 WHERE c.is_deleted = 0 AND c.is_deceased = 0
1252 SELECT rem.contact_id
1253 FROM civicrm_action_log rem INNER JOIN {$mapping->entity} e ON rem.entity_id = e.id
1254 WHERE rem.action_schedule_id = {$actionSchedule->id}
1255 AND rem.entity_table = '{$mapping->entity}'
1259 CRM_Core_DAO
::executeQuery($insertAdditionalSql);
1261 // if repeat is turned ON:
1262 if ($actionSchedule->is_repeat
) {
1263 $repeatEvent = ($actionSchedule->end_action
== 'before' ?
'DATE_SUB' : 'DATE_ADD') . "({$dateField}, INTERVAL {$actionSchedule->end_frequency_interval} {$actionSchedule->end_frequency_unit})";
1265 if ($actionSchedule->repetition_frequency_unit
== 'day') {
1266 $hrs = 24 * $actionSchedule->repetition_frequency_interval
;
1268 elseif ($actionSchedule->repetition_frequency_unit
== 'week') {
1269 $hrs = 24 * $actionSchedule->repetition_frequency_interval
* 7;
1271 elseif ($actionSchedule->repetition_frequency_unit
== 'month') {
1272 $hrs = "24*(DATEDIFF(DATE_ADD(latest_log_time, INTERVAL 1 MONTH ), latest_log_time))";
1274 elseif ($actionSchedule->repetition_frequency_unit
== 'year') {
1275 $hrs = "24*(DATEDIFF(DATE_ADD(latest_log_time, INTERVAL 1 YEAR ), latest_log_time))";
1278 $hrs = $actionSchedule->repetition_frequency_interval
;
1281 // (now <= repeat_end_time )
1282 $repeatEventClause = "'{$now}' <= {$repeatEvent}";
1283 // diff(now && logged_date_time) >= repeat_interval
1284 $havingClause = "HAVING TIMEDIFF({$now}, latest_log_time) >= TIME('{$hrs}:00:00')";
1285 $groupByClause = 'GROUP BY reminder.contact_id, reminder.entity_id, reminder.entity_table';
1286 $selectClause .= ', MAX(reminder.action_date_time) as latest_log_time';
1287 //CRM-15376 - do not send our reminders if original criteria no longer applies
1288 // the first part of the startDateClause array is the earliest the reminder can be sent. If the
1289 // event (e.g membership_end_date) has changed then the reminder may no longer apply
1290 // @todo - this only handles events that get moved later. Potentially they might get moved earlier
1291 $originalEventStartDateClause = empty($startDateClause) ?
'' : 'AND' . $startDateClause[0];
1292 $sqlInsertValues = "{$selectClause}
1295 INNER JOIN {$reminderJoinClause}
1296 {$whereClause} {$limitWhereClause} AND {$repeatEventClause} {$originalEventStartDateClause} {$notINClause}
1300 $valsqlInsertValues = CRM_Core_DAO
::executeQuery($sqlInsertValues, array(1 => array($actionSchedule->id
, 'Integer')));
1302 $arrValues = array();
1303 while ($valsqlInsertValues->fetch()) {
1304 $arrValues[] = "( {$valsqlInsertValues->contact_id}, {$valsqlInsertValues->entity_id}, '{$valsqlInsertValues->entity_table}',{$valsqlInsertValues->action_schedule_id} )";
1307 $valString = implode(',', $arrValues);
1311 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1312 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
1315 if ($isSendToAdditionalContacts) {
1316 $addSelect .= ', MAX(reminder.action_date_time) as latest_log_time';
1317 $sqlEndEventCheck = "
1318 SELECT * FROM {$table}
1319 {$whereClause} AND {$repeatEventClause} LIMIT 1";
1321 $daoCheck = CRM_Core_DAO
::executeQuery($sqlEndEventCheck);
1322 if ($daoCheck->fetch()) {
1323 $valSqlAdditionInsert = "
1325 FROM {$contactTable}
1327 INNER JOIN {$additionReminderClause}
1328 WHERE {$addWhere} AND c.is_deleted = 0 AND c.is_deceased = 0
1329 GROUP BY reminder.contact_id
1332 $daoForVals = CRM_Core_DAO
::executeQuery($valSqlAdditionInsert);
1333 $addValues = array();
1334 while ($daoForVals->fetch()) {
1335 $addValues[] = "( {$daoForVals->contact_id}, {$daoForVals->entity_id}, '{$daoForVals->entity_table}',{$daoForVals->action_schedule_id} )";
1337 $valString = implode(',', $addValues);
1341 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1342 CRM_Core_DAO
::executeQuery($query);
1353 * @return null|string
1355 public static function permissionedRelationships($field) {
1357 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
1358 FROM civicrm_membership m
1359 LEFT JOIN civicrm_membership cm ON cm.id = m.owner_membership_id
1360 LEFT JOIN civicrm_membership_type cmt ON cmt.id = m.membership_type_id
1361 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 )
1362 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 ) )
1363 WHERE m.owner_membership_id IS NOT NULL AND
1364 ( rel.is_permission_a_b = 0 OR rel.is_permission_b_a = 0)
1367 $excludeIds = array();
1368 $dao = CRM_Core_DAO
::executeQuery($query, array());
1369 while ($dao->fetch()) {
1370 if ($dao->slave_contact
== $dao->contact_id_a
&& $dao->is_permission_a_b
== 0) {
1371 $excludeIds[] = $dao->slave_contact
;
1373 elseif ($dao->slave_contact
== $dao->contact_id_b
&& $dao->is_permission_b_a
== 0) {
1374 $excludeIds[] = $dao->slave_contact
;
1378 if (!empty($excludeIds)) {
1379 $clause = "AND {$field} NOT IN ( " .implode(', ', $excludeIds) . ' ) ';
1387 * @param array $params
1391 public static function processQueue($now = NULL, $params = array()) {
1392 $now = $now ? CRM_Utils_Time
::setTime($now) : CRM_Utils_Time
::getTime();
1394 $mappings = self
::getMapping();
1395 foreach ($mappings as $mappingID => $mapping) {
1396 self
::buildRecipientContacts($mappingID, $now, $params);
1397 self
::sendMailings($mappingID, $now);
1402 'messages' => ts('Sent all scheduled reminders successfully'),
1409 * @param int $mappingID
1411 * @return null|string
1413 public static function isConfigured($id, $mappingID) {
1414 $queryString = "SELECT count(id) FROM civicrm_action_schedule
1415 WHERE mapping_id = %1 AND
1419 1 => array($mappingID, 'Integer'),
1420 2 => array($id, 'Integer'),
1422 return CRM_Core_DAO
::singleValueQuery($queryString, $params);
1426 * @param int $mappingID
1427 * @param $recipientType
1431 public static function getRecipientListing($mappingID, $recipientType) {
1433 if (!$mappingID ||
!$recipientType) {
1437 $mapping = self
::getMapping($mappingID);
1439 switch ($mapping['entity']) {
1440 case 'civicrm_participant':
1441 $eventContacts = CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
1442 if (empty($eventContacts[$recipientType])) {
1445 if ($eventContacts[$recipientType] == 'participant_role') {
1446 $options = CRM_Event_PseudoConstant
::participantRole();