3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 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 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
95 static function getSelection($id = NULL) {
96 $mapping = self
::getMapping($id);
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 a 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');
196 $sel5[$entityRecipient] = $eventContacts +
$options;
197 $recipientMapping +
= CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, '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 static function getSelection1($id = NULL) {
270 $mapping = self
::getMapping($id);
271 $sel4 = $sel5 = array();
273 'manual' => ts('Choose Recipient(s)'),
274 'group' => ts('Select a 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');
299 $sel5[$id] = $eventContacts +
$options;
300 $recipientMapping +
= CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name');
304 $sel5[$id] = $options;
311 'sel5' => $sel5[$id],
312 'recipientMapping' => $recipientMapping,
317 * Retrieve list of Scheduled Reminders
319 * @param bool $namesOnly return simple list of names
321 * @param null $entityValue
324 * @return array (reference) reminder list
328 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;
371 if ($entityValue and $id) {
373 WHERE cas.entity_value = $id AND
374 cam.entity_value = '$entityValue'";
379 1 => array($id, 'Integer'),
380 2 => array($entityValue, 'String'),
384 $dao = CRM_Core_DAO
::executeQuery($query);
385 while ($dao->fetch()) {
386 $list[$dao->id
]['id'] = $dao->id
;
387 $list[$dao->id
]['title'] = $dao->title
;
388 $list[$dao->id
]['start_action_offset'] = $dao->start_action_offset
;
389 $list[$dao->id
]['start_action_unit'] = $dao->start_action_unit
;
390 $list[$dao->id
]['start_action_condition'] = $dao->start_action_condition
;
391 $list[$dao->id
]['entityDate'] = ucwords(str_replace('_', ' ', $dao->entityDate
));
392 $list[$dao->id
]['absolute_date'] = $dao->absolute_date
;
394 $status = $dao->entityStatus
;
395 $statusArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityStatusIds
);
396 foreach ($statusArray as & $s) {
397 $s = CRM_Utils_Array
::value($s, $
$status);
399 $statusIds = implode(', ', $statusArray);
401 $value = $dao->entityValue
;
402 $valueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityValueIds
);
403 foreach ($valueArray as & $v) {
404 $v = CRM_Utils_Array
::value($v, $
$value);
406 $valueIds = implode(', ', $valueArray);
407 $list[$dao->id
]['entity'] = $entity[$dao->entity
];
408 $list[$dao->id
]['value'] = $valueIds;
409 $list[$dao->id
]['status'] = $statusIds;
410 $list[$dao->id
]['is_repeat'] = $dao->is_repeat
;
411 $list[$dao->id
]['is_active'] = $dao->is_active
;
422 * @param $tokenParams
425 * @throws CRM_Core_Exception
427 static function sendReminder($contactId, $to, $scheduleID, $from, $tokenParams) {
428 $email = $to['email'];
429 $phoneNumber = $to['phone'];
430 $schedule = new CRM_Core_DAO_ActionSchedule();
431 $schedule->id
= $scheduleID;
433 $domain = CRM_Core_BAO_Domain
::getDomain();
435 $hookTokens = array();
437 if ($schedule->find(TRUE)) {
438 $body_text = $schedule->body_text
;
439 $body_html = $schedule->body_html
;
440 $sms_body_text = $schedule->sms_body_text
;
441 $body_subject = $schedule->subject
;
443 $body_text = CRM_Utils_String
::htmlToText($body_html);
446 $params = array(array('contact_id', '=', $contactId, 0, 0));
447 list($contact, $_) = CRM_Contact_BAO_Query
::apiQuery($params);
450 $contact = reset($contact);
452 if (!$contact ||
is_a($contact, 'CRM_Core_Error')) {
456 // merge activity tokens with contact array
457 $contact = array_merge($contact, $tokenParams);
460 CRM_Utils_Hook
::tokenValues($contact, $contactId);
462 CRM_Utils_Hook
::tokens($hookTokens);
463 $categories = array_keys($hookTokens);
465 $type = array('body_html' => 'html', 'body_text' => 'text', 'sms_body_text' => 'text');
467 foreach ($type as $bodyType => $value) {
468 $dummy_mail = new CRM_Mailing_BAO_Mailing();
469 if ($bodyType == 'sms_body_text') {
470 $dummy_mail->body_text
= $
$bodyType;
473 $dummy_mail->$bodyType = $
$bodyType;
475 $tokens = $dummy_mail->getTokens();
478 CRM_Utils_Token
::replaceGreetingTokens($
$bodyType, NULL, $contact['contact_id']);
479 $
$bodyType = CRM_Utils_Token
::replaceDomainTokens($
$bodyType, $domain, TRUE, $tokens[$value], TRUE);
480 $
$bodyType = CRM_Utils_Token
::replaceContactTokens($
$bodyType, $contact, FALSE, $tokens[$value], FALSE, TRUE);
481 $
$bodyType = CRM_Utils_Token
::replaceComponentTokens($
$bodyType, $contact, $tokens[$value], TRUE, FALSE);
482 $
$bodyType = CRM_Utils_Token
::replaceHookTokens($
$bodyType, $contact, $categories, TRUE);
487 $sms_text = $sms_body_text;
489 $smarty = CRM_Core_Smarty
::singleton();
491 'text', 'html', 'sms_text') as $elem) {
492 $
$elem = $smarty->fetch("string:{$$elem}");
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 $messageSubject = CRM_Utils_Token
::replaceContactTokens($body_subject, $contact, FALSE, $subjectToken);
516 $messageSubject = CRM_Utils_Token
::replaceDomainTokens($messageSubject, $domain, TRUE, $subjectToken);
517 $messageSubject = CRM_Utils_Token
::replaceComponentTokens($messageSubject, $contact, $subjectToken, TRUE);
518 $messageSubject = CRM_Utils_Token
::replaceHookTokens($messageSubject, $contact, $categories, TRUE);
520 $messageSubject = $smarty->fetch("string:{$messageSubject}");
522 if ($schedule->mode
== 'SMS' or $schedule->mode
== 'User_Preference') {
523 $session = CRM_Core_Session
::singleton();
524 $userID = $session->get('userID') ?
$session->get('userID') : $contactId;
525 $smsParams = array('To' => $phoneNumber, 'provider_id' => $schedule->sms_provider_id
, 'activity_subject' => $messageSubject);
526 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
530 $activityParams = array(
531 'source_contact_id' => $userID,
532 'activity_type_id' => $activityTypeID,
533 'activity_date_time' => date('YmdHis'),
534 'subject' => $messageSubject,
535 'details' => $sms_text,
536 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
539 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
541 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 * Function to add the schedules reminders in the db
585 * @param array $params (reference ) an assoc array of name/value pairs
586 * @param array $ids the array that holds all the db ids
588 * @return object CRM_Core_DAO_ActionSchedule
593 static function add(&$params, $ids = array()) {
594 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
595 $actionSchedule->copyValues($params);
597 return $actionSchedule->save();
601 * Takes a bunch of params that are needed to match certain criteria and
602 * retrieves the relevant objects. It also stores all the retrieved
603 * values in the default array
605 * @param array $params (reference ) an assoc array of name/value pairs
606 * @param array $values (reference ) an assoc array to hold the flattened values
608 * @return object CRM_Core_DAO_ActionSchedule object on success, null otherwise
612 static function retrieve(&$params, &$values) {
613 if (empty($params)) {
616 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
618 $actionSchedule->copyValues($params);
620 if ($actionSchedule->find(TRUE)) {
621 $ids['actionSchedule'] = $actionSchedule->id
;
623 CRM_Core_DAO
::storeValues($actionSchedule, $values);
625 return $actionSchedule;
631 * Function to delete a Reminder
633 * @param int $id ID of the Reminder to be deleted.
638 static function del($id) {
640 $dao = new CRM_Core_DAO_ActionSchedule();
642 if ($dao->find(TRUE)) {
647 CRM_Core_Error
::fatal(ts('Invalid value passed to delete function.'));
651 * update the is_active flag in the db
653 * @param int $id id of the database record
654 * @param boolean $is_active value we want to set the is_active field
656 * @return Object DAO object on success, null otherwise
659 static function setIsActive($id, $is_active) {
660 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
667 * @throws CRM_Core_Exception
669 static function sendMailings($mappingID, $now) {
670 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
671 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
673 $mapping = new CRM_Core_DAO_ActionMapping();
674 $mapping->id
= $mappingID;
675 $mapping->find(TRUE);
677 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
678 $actionSchedule->mapping_id
= $mappingID;
679 $actionSchedule->is_active
= 1;
680 $actionSchedule->find(FALSE);
682 $tokenFields = array();
683 $session = CRM_Core_Session
::singleton();
685 while ($actionSchedule->fetch()) {
686 $extraSelect = $extraJoin = $extraWhere = $extraOn = '';
688 if ($actionSchedule->from_email
)
689 $fromEmailAddress = "$actionSchedule->from_name <$actionSchedule->from_email>";
692 if ($actionSchedule->record_activity
) {
693 if ($mapping->entity
== 'civicrm_membership') {
695 CRM_Core_OptionGroup
::getValue('activity_type', 'Membership Renewal Reminder', 'name');
699 CRM_Core_OptionGroup
::getValue('activity_type', 'Reminder Sent', 'name');
703 CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
706 if ($mapping->entity
== 'civicrm_activity') {
707 $tokenEntity = 'activity';
708 $tokenFields = array('activity_id', 'activity_type', 'subject', 'details', 'activity_date_time');
709 $extraSelect = ', ov.label as activity_type, e.id as activity_id';
711 INNER JOIN civicrm_option_group og ON og.name = 'activity_type'
712 INNER JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
713 $extraOn = ' AND e.is_current_revision = 1 AND e.is_deleted = 0 ';
714 if ($actionSchedule->limit_to
== 0) {
716 LEFT JOIN civicrm_option_group og ON og.name = 'activity_type'
717 LEFT JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
721 if ($mapping->entity
== 'civicrm_participant') {
722 $tokenEntity = 'event';
723 $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');
724 $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 ';
727 INNER JOIN civicrm_event ev ON e.event_id = ev.id
728 INNER JOIN civicrm_option_group og ON og.name = 'event_type'
729 INNER JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
730 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
731 LEFT JOIN civicrm_address address ON address.id = lb.address_id
732 LEFT JOIN civicrm_email email ON email.id = lb.email_id
733 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
735 if ($actionSchedule->limit_to
== 0) {
737 LEFT JOIN civicrm_event ev ON e.event_id = ev.id
738 LEFT JOIN civicrm_option_group og ON og.name = 'event_type'
739 LEFT JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
740 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
741 LEFT JOIN civicrm_address address ON address.id = lb.address_id
742 LEFT JOIN civicrm_email email ON email.id = lb.email_id
743 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
748 if ($mapping->entity
== 'civicrm_membership') {
749 $tokenEntity = 'membership';
750 $tokenFields = array('fee', 'id', 'join_date', 'start_date', 'end_date', 'status', 'type');
751 $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';
753 INNER JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
754 INNER JOIN civicrm_membership_status ms ON e.status_id = ms.id';
756 if ($actionSchedule->limit_to
== 0) {
758 LEFT JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
759 LEFT JOIN civicrm_membership_status ms ON e.status_id = ms.id';
763 if ($mapping->entity
== 'civicrm_contact') {
764 $tokenEntity = 'contact';
765 //TODO: get full list somewhere!
766 $tokenFields = array('birth_date', 'last_name');
767 //TODO: is there anything to add here?
770 $entityJoinClause = "INNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
771 if ($actionSchedule->limit_to
== 0) {
772 $entityJoinClause = "LEFT JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
773 $extraWhere .= " AND (e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact')";
775 $entityJoinClause .= $extraOn;
778 SELECT reminder.id as reminderID, reminder.contact_id as contactID, reminder.entity_table as entityTable, reminder.*, e.id as entityID, e.* {$extraSelect}
779 FROM civicrm_action_log reminder
782 WHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL
785 $dao = CRM_Core_DAO
::executeQuery($query,
786 array(1 => array($actionSchedule->id
, 'Integer'))
789 while ($dao->fetch()) {
790 $entityTokenParams = array();
791 foreach ($tokenFields as $field) {
792 if ($field == 'location') {
794 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
795 $loc['street_address'] = $dao->street_address
;
796 $loc['city'] = $dao->city
;
797 $loc['state_province'] = CRM_Utils_Array
::value($dao->state_province_id
, $stateProvince);
798 $loc['postal_code'] = $dao->postal_code
;
799 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address
::format($loc);
801 elseif ($field == 'info_url') {
802 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
804 elseif ($field == 'registration_url') {
805 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
807 elseif (in_array($field, array('start_date','end_date','join_date','activity_date_time'))) {
808 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date
::customFormat($dao->$field);
810 elseif ($field == 'balance') {
811 if ($dao->entityTable
== 'civicrm_contact') {
814 elseif (!empty($dao->entityID
)) {
815 $info = CRM_Contribute_BAO_Contribution
::getPaymentInfo($dao->entityID
, 'event');
816 $balancePay = CRM_Utils_Array
::value('balance', $info);
817 $balancePay = CRM_Utils_Money
::format($balancePay);
819 $entityTokenParams["{$tokenEntity}." . $field] = $balancePay;
821 elseif ($field == 'fee_amount') {
822 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Money
::format($dao->$field);
825 $entityTokenParams["{$tokenEntity}." . $field] = $dao->$field;
830 $errorMsg = $toEmail = $toPhoneNumber = '';
832 if ($actionSchedule->mode
== 'SMS' or $actionSchedule->mode
== 'User_Preference') {
833 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
834 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($dao->contactID
, FALSE, 'Mobile', $filters);
835 //to get primary mobile ph,if not get a first mobile phONE
836 if (!empty($toPhoneNumbers)) {
837 $toPhoneNumberDetails = reset($toPhoneNumbers);
838 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumberDetails);
839 //contact allows to send sms
843 if ($actionSchedule->mode
== 'Email' or $actionSchedule->mode
== 'User_Preference') {
844 $toEmail = CRM_Contact_BAO_Contact
::getPrimaryEmail($dao->contactID
);
846 if ($toEmail ||
!(empty($toPhoneNumber) or $toDoNotSms)) {
847 $to['email'] = $toEmail;
848 $to['phone'] = $toPhoneNumber;
850 CRM_Core_BAO_ActionSchedule
::sendReminder(
858 if (!$result ||
is_a($result, 'PEAR_Error')) {
859 // we could not send an email, for now we ignore, CRM-3406
865 $errorMsg = "Couldn\'t find recipient\'s email address.";
868 // update action log record
870 'id' => $dao->reminderID
,
871 'is_error' => $isError,
872 'message' => $errorMsg ?
$errorMsg : "null",
873 'action_date_time' => $now,
875 CRM_Core_BAO_ActionLog
::create($logParams);
877 // insert activity log record if needed
878 if ($actionSchedule->record_activity
&& !$isError) {
879 $activityParams = array(
880 'subject' => $actionSchedule->title
,
881 'details' => $actionSchedule->body_html
,
882 'source_contact_id' =>
883 $session->get('userID') ?
$session->get('userID') : $dao->contactID
,
884 'target_contact_id' => $dao->contactID
,
885 'activity_date_time' => date('YmdHis'),
886 'status_id' => $activityStatusID,
887 'activity_type_id' => $activityTypeID,
888 'source_record_id' => $dao->entityID
,
890 CRM_Activity_BAO_Activity
::create($activityParams);
901 * @param array $params
903 * @throws API_Exception
905 static function buildRecipientContacts($mappingID, $now, $params = array()) {
906 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
907 $actionSchedule->mapping_id
= $mappingID;
908 $actionSchedule->is_active
= 1;
909 if(!empty($params)) {
910 _civicrm_api3_dao_set_filter($actionSchedule, $params, FALSE, 'ActionSchedule');
912 $actionSchedule->find();
914 while ($actionSchedule->fetch()) {
915 $mapping = new CRM_Core_DAO_ActionMapping();
916 $mapping->id
= $mappingID;
917 $mapping->find(TRUE);
919 // note: $where - this filtering applies for both
920 // 'limit to' and 'addition to' options
921 // $limitWhere - this filtering applies only for
923 $select = $join = $where = $limitWhere = array();
924 $limitTo = $actionSchedule->limit_to
;
925 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
926 trim($actionSchedule->entity_value
, CRM_Core_DAO
::VALUE_SEPARATOR
)
928 $value = implode(',', $value);
930 $status = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
931 trim($actionSchedule->entity_status
, CRM_Core_DAO
::VALUE_SEPARATOR
)
933 $status = implode(',', $status);
935 $anniversary = false;
937 if (!CRM_Utils_System
::isNull($mapping->entity_recipient
)) {
938 $recipientOptions = CRM_Core_OptionGroup
::values($mapping->entity_recipient
, FALSE, FALSE, FALSE, NULL, 'name');
940 $from = "{$mapping->entity} e";
942 if ($mapping->entity
== 'civicrm_activity') {
943 $contactField = 'r.contact_id';
944 $table = 'civicrm_activity e';
945 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
946 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
947 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
948 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
951 // including the activity target contacts if 'in addition' is defined
952 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
955 switch (CRM_Utils_Array
::value($actionSchedule->recipient
, $recipientOptions)) {
956 case 'Activity Assignees':
957 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$assigneeID}";
960 case 'Activity Source':
961 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$sourceID}";
965 case 'Activity Targets':
966 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
970 // build where clause
971 if (!empty($value)) {
972 $where[] = "e.activity_type_id IN ({$value})";
975 $where[] = "e.activity_type_id IS NULL";
977 if (!empty($status)) {
978 $where[] = "e.status_id IN ({$status})";
980 $where[] = ' e.is_current_revision = 1 ';
981 $where[] = ' e.is_deleted = 0 ';
983 $dateField = 'e.activity_date_time';
986 if ($mapping->entity
== 'civicrm_participant') {
987 $table = 'civicrm_event r';
988 $contactField = 'e.contact_id';
989 $join[] = 'INNER JOIN civicrm_event r ON e.event_id = r.id';
990 if ($actionSchedule->recipient_listing
&& $limitTo) {
991 $rList = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
992 trim($actionSchedule->recipient_listing
, CRM_Core_DAO
::VALUE_SEPARATOR
)
994 $rList = implode(',', $rList);
996 switch ($recipientOptions[$actionSchedule->recipient
]) {
997 case 'participant_role':
998 $where[] = "e.role_id IN ({$rList})";
1006 // build where clause
1007 if (!empty($value)) {
1008 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IN ({$value})" : "r.id IN ({$value})";
1011 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IS NULL" : "r.id IS NULL";
1014 // participant status criteria not to be implemented
1015 // for additional recipients
1016 if (!empty($status)) {
1017 $limitWhere[] = "e.status_id IN ({$status})";
1020 $where[] = 'r.is_active = 1';
1021 $where[] = 'r.is_template = 0';
1022 $dateField = str_replace('event_', 'r.', $actionSchedule->start_action_date
);
1026 if ($mapping->entity
== 'civicrm_membership') {
1027 $contactField = 'e.contact_id';
1028 $table = 'civicrm_membership e';
1029 // build where clause
1030 if ( $status == 2 ) {
1031 //auto-renew memberships
1032 $where[] = "e.contribution_recur_id IS NOT NULL ";
1034 elseif ( $status == 1 ) {
1035 $where[] = "e.contribution_recur_id IS NULL ";
1038 // build where clause
1039 if (!empty($value)) {
1040 $where[] = "e.membership_type_id IN ({$value})";
1043 $where[] = "e.membership_type_id IS NULL";
1046 $where[] = "( e.is_override IS NULL OR e.is_override = 0 )";
1047 $dateField = str_replace('membership_', 'e.', $actionSchedule->start_action_date
);
1048 $notINClause = self
::permissionedRelationships($contactField);
1050 $membershipStatus = CRM_Member_PseudoConstant
::membershipStatus(NULL, "(is_current_member = 1 OR name = 'Expired')", 'id');
1051 $mStatus = implode (',', $membershipStatus);
1052 $where[] = "e.status_id IN ({$mStatus})";
1055 if ($mapping->entity
== 'civicrm_contact') {
1056 if ($value == 'birth_date') {
1057 $dateDBField = 'birth_date';
1058 $table = 'civicrm_contact e';
1059 $contactField = 'e.id';
1060 $where[] = 'e.is_deleted = 0';
1061 $where[] = 'e.is_deceased = 0';
1065 $customFieldParams = array('id' => substr($value, 7));
1066 $customGroup = $customField = array();
1067 CRM_Core_BAO_CustomField
::retrieve($customFieldParams, $customField);
1068 $dateDBField = $customField['column_name'];
1069 $customGroupParams = array('id' => $customField['custom_group_id'], $customGroup);
1070 CRM_Core_BAO_CustomGroup
::retrieve($customGroupParams, $customGroup);
1071 $from = $table = "{$customGroup['table_name']} e";
1072 $contactField = 'e.entity_id';
1073 $where[] = '1'; // possible to have no "where" in this case
1076 $status_ = explode(',', $status);
1077 if (in_array(2, $status_)) {
1078 // anniversary mode:
1079 $dateField = 'DATE_ADD(e.' . $dateDBField . ', INTERVAL ROUND(DATEDIFF(DATE(' . $now . '), e.' . $dateDBField . ') / 365) YEAR)';
1080 $anniversary = true;
1084 $dateField = 'e.' . $dateDBField;
1086 // TODO get this working
1088 // TODO: Make sure everything's provided for repetition, etc.
1091 // CRM-13577 Introduce Smart Groups Handling
1092 if ($actionSchedule->group_id
) {
1094 // Need to check if its a smart group or not
1095 // Then decide which table to join onto the query
1096 $group = CRM_Contact_DAO_Group
::getTableName();
1098 // Get the group information
1100 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
1102 WHERE $group.id = {$actionSchedule->group_id}
1105 $groupDAO = CRM_Core_DAO
::executeQuery($sql);
1106 $isSmartGroup = FALSE;
1108 $groupDAO->fetch() &&
1109 !empty($groupDAO->saved_search_id
)
1111 // Check that the group is in place in the cache and up to date
1112 CRM_Contact_BAO_GroupContactCache
::check($actionSchedule->group_id
);
1113 // Set smart group flag
1114 $isSmartGroup = TRUE;
1117 // CRM-13577 End Introduce Smart Groups Handling
1120 if ($actionSchedule->group_id
) {
1121 // CRM-13577 If smart group then use Cache table
1122 if ($isSmartGroup) {
1123 $join[] = "INNER JOIN civicrm_group_contact_cache grp ON {$contactField} = grp.contact_id";
1124 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1126 $join[] = "INNER JOIN civicrm_group_contact grp ON {$contactField} = grp.contact_id AND grp.status = 'Added'";
1127 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1130 elseif (!empty($actionSchedule->recipient_manual
)) {
1131 $rList = CRM_Utils_Type
::escape($actionSchedule->recipient_manual
, 'String');
1132 $where[] = "{$contactField} IN ({$rList})";
1136 $addGroup = $addWhere = '';
1137 if ($actionSchedule->group_id
) {
1138 // CRM-13577 If smart group then use Cache table
1139 if ($isSmartGroup) {
1140 $addGroup = " INNER JOIN civicrm_group_contact_cache grp ON c.id = grp.contact_id";
1141 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1143 $addGroup = " INNER JOIN civicrm_group_contact grp ON c.id = grp.contact_id AND grp.status = 'Added'";
1144 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1147 if (!empty($actionSchedule->recipient_manual
)) {
1148 $rList = CRM_Utils_Type
::escape($actionSchedule->recipient_manual
, 'String');
1149 $addWhere = "c.id IN ({$rList})";
1153 $select[] = "{$contactField} as contact_id";
1154 $select[] = 'e.id as entity_id';
1155 $select[] = "'{$mapping->entity}' as entity_table";
1156 $select[] = "{$actionSchedule->id} as action_schedule_id";
1157 $reminderJoinClause = "civicrm_action_log reminder ON reminder.contact_id = {$contactField} AND
1158 reminder.entity_id = e.id AND
1159 reminder.entity_table = '{$mapping->entity}' AND
1160 reminder.action_schedule_id = %1";
1163 // only consider reminders less than 11 months ago
1164 $reminderJoinClause .= " AND reminder.action_date_time > DATE_SUB({$now}, INTERVAL 11 MONTH)";
1167 if ($table != 'civicrm_contact e') {
1168 $join[] = "INNER JOIN civicrm_contact c ON c.id = {$contactField} AND c.is_deleted = 0 AND c.is_deceased = 0 ";
1171 if ($actionSchedule->start_action_date
) {
1172 $startDateClause = array();
1173 $op = ($actionSchedule->start_action_condition
== 'before' ?
'<=' : '>=');
1174 $operator = ($actionSchedule->start_action_condition
== 'before' ?
'DATE_SUB' : 'DATE_ADD');
1175 $date = $operator . "({$dateField}, INTERVAL {$actionSchedule->start_action_offset} {$actionSchedule->start_action_unit})";
1176 $startDateClause[] = "'{$now}' >= {$date}";
1177 if ($mapping->entity
== 'civicrm_participant') {
1178 $startDateClause[] = $operator. "({$now}, INTERVAL 1 DAY ) {$op} " . $dateField;
1181 $startDateClause[] = "DATE_SUB({$now}, INTERVAL 1 DAY ) <= {$date}";
1184 $startDate = implode(' AND ', $startDateClause);
1186 elseif ($actionSchedule->absolute_date
) {
1187 $startDate = "DATEDIFF(DATE('{$now}'),'{$actionSchedule->absolute_date}') = 0";
1190 // ( now >= date_built_from_start_time ) OR ( now = absolute_date )
1191 $dateClause = "reminder.id IS NULL AND {$startDate}";
1193 // start composing query
1194 $selectClause = 'SELECT ' . implode(', ', $select);
1195 $fromClause = "FROM $from";
1196 $joinClause = !empty($join) ?
implode(' ', $join) : '';
1197 $whereClause = 'WHERE ' . implode(' AND ', $where);
1198 $limitWhereClause = '';
1199 if (!empty($limitWhere)) {
1200 $limitWhereClause = ' AND ' . implode(' AND ', $limitWhere);
1204 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1208 LEFT JOIN {$reminderJoinClause}
1209 {$whereClause} {$limitWhereClause} AND {$dateClause} {$notINClause}
1211 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
1213 if ($limitTo == 0 && (!empty($addGroup) ||
!empty($addWhere))) {
1214 $additionWhere = ' WHERE ';
1215 if ($actionSchedule->start_action_date
) {
1216 $additionWhere = $whereClause . ' AND ';
1218 $contactTable = "civicrm_contact c";
1219 $addSelect = "SELECT c.id as contact_id, c.id as entity_id, 'civicrm_contact' as entity_table, {$actionSchedule->id} as action_schedule_id";
1220 $additionReminderClause = "civicrm_action_log reminder ON reminder.contact_id = c.id AND
1221 reminder.entity_id = c.id AND
1222 reminder.entity_table = 'civicrm_contact' AND
1223 reminder.action_schedule_id = {$actionSchedule->id}";
1224 $addWhereClause = '';
1226 $addWhereClause = "AND {$addWhere}";
1228 $insertAdditionalSql ="
1229 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1231 FROM ({$contactTable})
1232 LEFT JOIN {$additionReminderClause}
1234 WHERE c.is_deleted = 0 AND c.is_deceased = 0
1238 SELECT rem.contact_id
1239 FROM civicrm_action_log rem INNER JOIN {$mapping->entity} e ON rem.entity_id = e.id
1240 WHERE rem.action_schedule_id = {$actionSchedule->id}
1241 AND rem.entity_table = '{$mapping->entity}'
1245 CRM_Core_DAO
::executeQuery($insertAdditionalSql);
1247 // if repeat is turned ON:
1248 if ($actionSchedule->is_repeat
) {
1249 $repeatEvent = ($actionSchedule->end_action
== 'before' ?
'DATE_SUB' : 'DATE_ADD') . "({$dateField}, INTERVAL {$actionSchedule->end_frequency_interval} {$actionSchedule->end_frequency_unit})";
1251 if ($actionSchedule->repetition_frequency_unit
== 'day') {
1252 $hrs = 24 * $actionSchedule->repetition_frequency_interval
;
1254 elseif ($actionSchedule->repetition_frequency_unit
== 'week') {
1255 $hrs = 24 * $actionSchedule->repetition_frequency_interval
* 7;
1257 elseif ($actionSchedule->repetition_frequency_unit
== 'month') {
1258 $hrs = "24*(DATEDIFF(DATE_ADD(latest_log_time, INTERVAL 1 MONTH ), latest_log_time))";
1260 elseif ($actionSchedule->repetition_frequency_unit
== 'year') {
1261 $hrs = "24*(DATEDIFF(DATE_ADD(latest_log_time, INTERVAL 1 YEAR ), latest_log_time))";
1264 $hrs = $actionSchedule->repetition_frequency_interval
;
1267 // (now <= repeat_end_time )
1268 $repeatEventClause = "'{$now}' <= {$repeatEvent}";
1269 // diff(now && logged_date_time) >= repeat_interval
1270 $havingClause = "HAVING TIMEDIFF({$now}, latest_log_time) >= TIME('{$hrs}:00:00')";
1271 $groupByClause = 'GROUP BY reminder.contact_id, reminder.entity_id, reminder.entity_table';
1272 $selectClause .= ', MAX(reminder.action_date_time) as latest_log_time';
1273 //CRM-15376 - do not send our reminders if original criteria no longer applies
1274 // the first part of the startDateClause array is the earliest the reminder can be sent. If the
1275 // event (e.g membership_end_date) has changed then the reminder may no longer apply
1276 // @todo - this only handles events that get moved later. Potentially they might get moved earlier
1277 $originalEventStartDateClause = empty($startDateClause) ?
'' : 'AND' . $startDateClause[0];
1278 $sqlInsertValues = "{$selectClause}
1281 INNER JOIN {$reminderJoinClause}
1282 {$whereClause} {$limitWhereClause} AND {$repeatEventClause} {$originalEventStartDateClause} {$notINClause}
1286 $valsqlInsertValues = CRM_Core_DAO
::executeQuery($sqlInsertValues, array(1 => array($actionSchedule->id
, 'Integer')));
1288 $arrValues = array();
1289 while ($valsqlInsertValues->fetch()) {
1290 $arrValues[] = "( {$valsqlInsertValues->contact_id}, {$valsqlInsertValues->entity_id}, '{$valsqlInsertValues->entity_table}',{$valsqlInsertValues->action_schedule_id} )";
1293 $valString = implode(',', $arrValues);
1297 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1298 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
1301 if ($limitTo == 0) {
1302 $addSelect .= ', MAX(reminder.action_date_time) as latest_log_time';
1303 $sqlEndEventCheck = "
1304 SELECT * FROM {$table}
1305 {$whereClause} AND {$repeatEventClause} LIMIT 1";
1307 $daoCheck = CRM_Core_DAO
::executeQuery($sqlEndEventCheck);
1308 if ($daoCheck->fetch()) {
1309 $valSqlAdditionInsert = "
1311 FROM {$contactTable}
1313 INNER JOIN {$additionReminderClause}
1314 WHERE {$addWhere} AND c.is_deleted = 0 AND c.is_deceased = 0
1315 GROUP BY reminder.contact_id
1318 $daoForVals = CRM_Core_DAO
::executeQuery($valSqlAdditionInsert);
1319 $addValues = array();
1320 while ($daoForVals->fetch()) {
1321 $addValues[] = "( {$daoForVals->contact_id}, {$daoForVals->entity_id}, '{$daoForVals->entity_table}',{$daoForVals->action_schedule_id} )";
1323 $valString = implode(',', $addValues);
1327 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1328 CRM_Core_DAO
::executeQuery($query);
1339 * @return null|string
1341 static function permissionedRelationships($field) {
1343 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
1344 FROM civicrm_membership m
1345 LEFT JOIN civicrm_membership cm ON cm.id = m.owner_membership_id
1346 LEFT JOIN civicrm_membership_type cmt ON cmt.id = m.membership_type_id
1347 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 )
1348 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 ) )
1349 WHERE m.owner_membership_id IS NOT NULL AND
1350 ( rel.is_permission_a_b = 0 OR rel.is_permission_b_a = 0)
1353 $excludeIds = array();
1354 $dao = CRM_Core_DAO
::executeQuery($query, array());
1355 while ($dao->fetch()) {
1356 if ($dao->slave_contact
== $dao->contact_id_a
&& $dao->is_permission_a_b
== 0) {
1357 $excludeIds[] = $dao->slave_contact
;
1359 elseif ($dao->slave_contact
== $dao->contact_id_b
&& $dao->is_permission_b_a
== 0) {
1360 $excludeIds[] = $dao->slave_contact
;
1364 if (!empty($excludeIds)) {
1365 $clause = "AND {$field} NOT IN ( " .implode(', ', $excludeIds) . ' ) ';
1373 * @param array $params
1377 static function processQueue($now = NULL, $params = array()) {
1378 $now = $now ? CRM_Utils_Time
::setTime($now) : CRM_Utils_Time
::getTime();
1380 $mappings = self
::getMapping();
1381 foreach ($mappings as $mappingID => $mapping) {
1382 self
::buildRecipientContacts($mappingID, $now, $params);
1383 self
::sendMailings($mappingID, $now);
1388 'messages' => ts('Sent all scheduled reminders successfully'),
1397 * @return null|string
1399 static function isConfigured($id, $mappingID) {
1400 $queryString = "SELECT count(id) FROM civicrm_action_schedule
1401 WHERE mapping_id = %1 AND
1405 1 => array($mappingID, 'Integer'),
1406 2 => array($id, 'Integer'),
1408 return CRM_Core_DAO
::singleValueQuery($queryString, $params);
1413 * @param $recipientType
1417 static function getRecipientListing($mappingID, $recipientType) {
1419 if (!$mappingID ||
!$recipientType) {
1423 $mapping = self
::getMapping($mappingID);
1425 switch ($mapping['entity']) {
1426 case 'civicrm_participant':
1427 $eventContacts = CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1428 if (empty($eventContacts[$recipientType])) {
1431 if ($eventContacts[$recipientType] == 'participant_role') {
1432 $options = CRM_Event_PseudoConstant
::participantRole();