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
93 * associated array of all the drop downs in the form
96 public static function getSelection($id = NULL) {
97 $mapping = self
::getMapping();
98 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
99 $activityType = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE);
101 $participantStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label');
102 $event = CRM_Event_PseudoConstant
::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
103 $eventType = CRM_Event_PseudoConstant
::eventType();
104 $eventTemplate = CRM_Event_PseudoConstant
::eventTemplates();
105 $autoRenew = CRM_Core_OptionGroup
::values('auto_renew_options');
106 $membershipType = CRM_Member_PseudoConstant
::membershipType();
107 $dateFieldParams = array('data_type' => 'Date');
108 $dateFields = self
::getDateFields();
109 $contactOptions = CRM_Core_OptionGroup
::values('contact_date_reminder_options');
111 asort($activityType);
113 $sel1 = $sel2 = $sel3 = $sel4 = $sel5 = array();
115 'manual' => ts('Choose Recipient(s)'),
116 'group' => ts('Select Group'),
119 $entityMapping = array();
120 $recipientMapping = array_combine(array_keys($options), array_keys($options));
126 foreach ($mapping as $value) {
127 $entityValue = CRM_Utils_Array
::value('entity_value', $value);
128 $entityStatus = CRM_Utils_Array
::value('entity_status', $value);
129 $entityRecipient = CRM_Utils_Array
::value('entity_recipient', $value);
130 $valueLabel = array('- ' . strtolower(CRM_Utils_Array
::value('entity_value_label', $value)) . ' -');
131 $key = CRM_Utils_Array
::value('id', $value);
132 $entityMapping[$key] = CRM_Utils_Array
::value('entity', $value);
135 switch ($entityValue) {
136 case 'activity_type':
137 if ($value['entity'] == 'civicrm_activity') {
138 $sel1Val = ts('Activity');
140 $sel2[$key] = $valueLabel +
$activityType;
144 if ($value['entity'] == 'civicrm_participant') {
145 $sel1Val = ts('Event Type');
147 $sel2[$key] = $valueLabel +
$eventType;
150 case 'event_template':
151 if ($value['entity'] == 'civicrm_participant') {
152 $sel1Val = ts('Event Template');
154 $sel2[$key] = $valueLabel +
$eventTemplate;
157 case 'civicrm_event':
158 if ($value['entity'] == 'civicrm_participant') {
159 $sel1Val = ts('Event Name');
161 $sel2[$key] = $valueLabel +
$event;
164 case 'civicrm_membership_type':
165 if ($value['entity'] == 'civicrm_membership') {
166 $sel1Val = ts('Membership');
168 $sel2[$key] = $valueLabel +
$membershipType;
171 case 'civicrm_contact':
172 if ($value['entity'] == 'civicrm_contact') {
173 $sel1Val = ts('Contact');
175 $sel2[$key] = $dateFields;
178 $sel1[$key] = $sel1Val;
181 if ($startDate = CRM_Utils_Array
::value('entity_date_start', $value)) {
182 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
184 if ($endDate = CRM_Utils_Array
::value('entity_date_end', $value)) {
185 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
188 switch ($entityRecipient) {
189 case 'activity_contacts':
190 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts');
191 $sel5[$entityRecipient] = $activityContacts +
$options;
192 $recipientMapping +
= CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
195 case 'event_contacts':
196 $eventContacts = CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name');
197 $sel5[$entityRecipient] = $eventContacts +
$options;
198 $recipientMapping +
= CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
202 $sel5[$entityRecipient] = $options;
209 foreach ($mapping as $value) {
210 $entityStatus = CRM_Utils_Array
::value('entity_status', $value);
211 $statusLabel = array('- ' . strtolower(CRM_Utils_Array
::value('entity_status_label', $value)) . ' -');
212 $id = CRM_Utils_Array
::value('id', $value);
214 switch ($entityStatus) {
215 case 'activity_status':
216 foreach ($sel3[$id] as $kkey => & $vval) {
217 $vval = $statusLabel +
$activityStatus;
221 case 'civicrm_participant_status_type':
222 foreach ($sel3[$id] as $kkey => & $vval) {
223 $vval = $statusLabel +
$participantStatus;
227 case 'auto_renew_options':
228 foreach ($sel3[$id] as $kkey => & $vval) {
231 $auto = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $kkey, 'auto_renew');
234 $vval = $statusLabel +
$autoRenew;
237 $vval = $statusLabel;
242 case 'contact_date_reminder_options':
243 foreach ($sel3[$id] as $kkey => & $vval) {
244 $vval = $contactOptions;
260 'entityMapping' => $entityMapping,
261 'recipientMapping' => $recipientMapping,
270 public static function getSelection1($id = NULL) {
271 $mapping = self
::getMapping($id);
272 $sel4 = $sel5 = array();
274 'manual' => ts('Choose Recipient(s)'),
275 'group' => ts('Select Group'),
278 $recipientMapping = array_combine(array_keys($options), array_keys($options));
280 foreach ($mapping as $value) {
281 $entityRecipient = CRM_Utils_Array
::value('entity_recipient', $value);
282 $key = CRM_Utils_Array
::value('id', $value);
284 if ($startDate = CRM_Utils_Array
::value('entity_date_start', $value)) {
285 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
287 if ($endDate = CRM_Utils_Array
::value('entity_date_end', $value)) {
288 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
291 switch ($entityRecipient) {
292 case 'activity_contacts':
293 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts');
294 $sel5[$id] = $activityContacts +
$options;
295 $recipientMapping +
= CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
298 case 'event_contacts':
299 $eventContacts = CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name');
300 $sel5[$id] = $eventContacts +
$options;
301 $recipientMapping +
= CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
305 $sel5[$id] = $options;
312 'sel5' => $sel5[$id],
313 'recipientMapping' => $recipientMapping,
318 * Retrieve list of Scheduled Reminders
320 * @param bool $namesOnly
321 * Return simple list of names.
323 * @param null $entityValue
327 * (reference) reminder list
330 public static function &getList($namesOnly = FALSE, $entityValue = NULL, $id = NULL) {
331 $activity_type = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE);
332 $activity_status = CRM_Core_PseudoConstant
::activityStatus();
334 $event_type = CRM_Event_PseudoConstant
::eventType();
335 $civicrm_event = CRM_Event_PseudoConstant
::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
336 $civicrm_participant_status_type = CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label');
337 $event_template = CRM_Event_PseudoConstant
::eventTemplates();
338 $civicrm_contact = self
::getDateFields();
340 $auto_renew_options = CRM_Core_OptionGroup
::values('auto_renew_options');
341 $contact_date_reminder_options = CRM_Core_OptionGroup
::values('contact_date_reminder_options');
342 $civicrm_membership_type = CRM_Member_PseudoConstant
::membershipType();
345 'civicrm_activity' => 'Activity',
346 'civicrm_participant' => 'Event',
347 'civicrm_membership' => 'Member',
348 'civicrm_contact' => 'Contact',
356 cam.entity_value as entityValue,
357 cas.entity_value as entityValueIds,
358 cam.entity_status as entityStatus,
359 cas.entity_status as entityStatusIds,
360 cas.start_action_date as entityDate,
361 cas.start_action_offset,
362 cas.start_action_unit,
363 cas.start_action_condition,
368 FROM civicrm_action_schedule cas
369 LEFT JOIN civicrm_action_mapping cam ON (cam.id = cas.mapping_id)
371 $params = CRM_Core_DAO
::$_nullArray;
372 $where = " WHERE 1 ";
373 if ($entityValue and $id) {
375 AND cas.entity_value = $id AND
376 cam.entity_value = '$entityValue'";
379 1 => array($id, 'Integer'),
380 2 => array($entityValue, 'String'),
383 $where .= " AND cas.used_for IS NULL";
385 $dao = CRM_Core_DAO
::executeQuery($query);
386 while ($dao->fetch()) {
387 $list[$dao->id
]['id'] = $dao->id
;
388 $list[$dao->id
]['title'] = $dao->title
;
389 $list[$dao->id
]['start_action_offset'] = $dao->start_action_offset
;
390 $list[$dao->id
]['start_action_unit'] = $dao->start_action_unit
;
391 $list[$dao->id
]['start_action_condition'] = $dao->start_action_condition
;
392 $list[$dao->id
]['entityDate'] = ucwords(str_replace('_', ' ', $dao->entityDate
));
393 $list[$dao->id
]['absolute_date'] = $dao->absolute_date
;
395 $status = $dao->entityStatus
;
396 $statusArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityStatusIds
);
397 foreach ($statusArray as & $s) {
398 $s = CRM_Utils_Array
::value($s, $
$status);
400 $statusIds = implode(', ', $statusArray);
402 $value = $dao->entityValue
;
403 $valueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityValueIds
);
404 foreach ($valueArray as & $v) {
405 $v = CRM_Utils_Array
::value($v, $
$value);
407 $valueIds = implode(', ', $valueArray);
408 $list[$dao->id
]['entity'] = $entity[$dao->entity
];
409 $list[$dao->id
]['value'] = $valueIds;
410 $list[$dao->id
]['status'] = $statusIds;
411 $list[$dao->id
]['is_repeat'] = $dao->is_repeat
;
412 $list[$dao->id
]['is_active'] = $dao->is_active
;
419 * @param int $contactId
421 * @param int $scheduleID
423 * @param array $tokenParams
426 * @throws CRM_Core_Exception
428 public static function sendReminder($contactId, $to, $scheduleID, $from, $tokenParams) {
429 $email = $to['email'];
430 $phoneNumber = $to['phone'];
431 $schedule = new CRM_Core_DAO_ActionSchedule();
432 $schedule->id
= $scheduleID;
434 $domain = CRM_Core_BAO_Domain
::getDomain();
436 $hookTokens = array();
438 if ($schedule->find(TRUE)) {
439 $body_text = $schedule->body_text
;
440 $body_html = $schedule->body_html
;
441 $sms_body_text = $schedule->sms_body_text
;
442 $body_subject = $schedule->subject
;
444 $body_text = CRM_Utils_String
::htmlToText($body_html);
447 $params = array(array('contact_id', '=', $contactId, 0, 0));
448 list($contact, $_) = CRM_Contact_BAO_Query
::apiQuery($params);
451 $contact = reset($contact);
453 if (!$contact ||
is_a($contact, 'CRM_Core_Error')) {
457 // merge activity tokens with contact array
458 $contact = array_merge($contact, $tokenParams);
461 CRM_Utils_Hook
::tokenValues($contact, $contactId);
463 CRM_Utils_Hook
::tokens($hookTokens);
464 $categories = array_keys($hookTokens);
466 $type = array('body_html' => 'html', 'body_text' => 'text', 'sms_body_text' => 'text');
468 foreach ($type as $bodyType => $value) {
469 $dummy_mail = new CRM_Mailing_BAO_Mailing();
470 if ($bodyType == 'sms_body_text') {
471 $dummy_mail->body_text
= $
$bodyType;
474 $dummy_mail->$bodyType = $
$bodyType;
476 $tokens = $dummy_mail->getTokens();
479 CRM_Utils_Token
::replaceGreetingTokens($
$bodyType, NULL, $contact['contact_id']);
480 $
$bodyType = CRM_Utils_Token
::replaceDomainTokens($
$bodyType, $domain, TRUE, $tokens[$value], TRUE);
481 $
$bodyType = CRM_Utils_Token
::replaceContactTokens($
$bodyType, $contact, FALSE, $tokens[$value], FALSE, TRUE);
482 $
$bodyType = CRM_Utils_Token
::replaceComponentTokens($
$bodyType, $contact, $tokens[$value], TRUE, FALSE);
483 $
$bodyType = CRM_Utils_Token
::replaceHookTokens($
$bodyType, $contact, $categories, TRUE);
488 $sms_text = $sms_body_text;
490 $smarty = CRM_Core_Smarty
::singleton();
492 'text', 'html', 'sms_text') as $elem) {
493 $
$elem = $smarty->fetch("string:{$$elem}");
496 //@todo - this next section is a duplicate of function CRM_Utils_Token::getTokens
498 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
504 $subjectToken = NULL;
506 foreach ($matches[1] as $token) {
507 list($type, $name) = preg_split('/\./', $token, 2);
509 if (!isset($subjectToken[$type])) {
510 $subjectToken[$type] = array();
512 $subjectToken[$type][] = $name;
517 // @todo this (along with the copy-&-paste chunk above is a commonly repeated chunk of code & should be in a re-usable function
518 $messageSubject = CRM_Utils_Token
::replaceContactTokens($body_subject, $contact, FALSE, $subjectToken);
519 $messageSubject = CRM_Utils_Token
::replaceDomainTokens($messageSubject, $domain, TRUE, $subjectToken);
520 $messageSubject = CRM_Utils_Token
::replaceComponentTokens($messageSubject, $contact, $subjectToken, TRUE);
521 $messageSubject = CRM_Utils_Token
::replaceHookTokens($messageSubject, $contact, $categories, TRUE);
523 $messageSubject = $smarty->fetch("string:{$messageSubject}");
525 if ($schedule->mode
== 'SMS' or $schedule->mode
== 'User_Preference') {
526 $session = CRM_Core_Session
::singleton();
527 $userID = $session->get('userID') ?
$session->get('userID') : $contactId;
528 $smsParams = array('To' => $phoneNumber, 'provider_id' => $schedule->sms_provider_id
, 'activity_subject' => $messageSubject);
529 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
533 $activityParams = array(
534 'source_contact_id' => $userID,
535 'activity_type_id' => $activityTypeID,
536 'activity_date_time' => date('YmdHis'),
537 'subject' => $messageSubject,
538 'details' => $sms_text,
539 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
542 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
544 CRM_Activity_BAO_Activity
::sendSMSMessage($contactId,
552 if ($schedule->mode
== 'Email' or $schedule->mode
== 'User_Preference') {
553 // set up the parameters for CRM_Utils_Mail::send
555 'groupName' => 'Scheduled Reminder Sender',
557 'toName' => $contact['display_name'],
559 'subject' => $messageSubject,
560 'entity' => 'action_schedule',
561 'entity_id' => $scheduleID,
564 if (!$html ||
$contact['preferred_mail_format'] == 'Text' ||
565 $contact['preferred_mail_format'] == 'Both'
567 // render the & entities in text mode, so that the links work
568 $mailParams['text'] = str_replace('&', '&', $text);
570 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
571 $contact['preferred_mail_format'] == 'Both'
574 $mailParams['html'] = $html;
576 $result = CRM_Utils_Mail
::send($mailParams);
585 * Add the schedules reminders in the db
587 * @param array $params
588 * (reference ) an assoc array of name/value pairs.
590 * The array that holds all the db ids.
592 * @return CRM_Core_DAO_ActionSchedule
595 public static function add(&$params, $ids = array()) {
596 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
597 $actionSchedule->copyValues($params);
599 return $actionSchedule->save();
603 * Takes a bunch of params that are needed to match certain criteria and
604 * retrieves the relevant objects. It also stores all the retrieved
605 * values in the default array
607 * @param array $params
608 * (reference ) an assoc array of name/value pairs.
609 * @param array $values
610 * (reference ) an assoc array to hold the flattened values.
612 * @return CRM_Core_DAO_ActionSchedule object on success, null otherwise
615 public static function retrieve(&$params, &$values) {
616 if (empty($params)) {
619 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
621 $actionSchedule->copyValues($params);
623 if ($actionSchedule->find(TRUE)) {
624 $ids['actionSchedule'] = $actionSchedule->id
;
626 CRM_Core_DAO
::storeValues($actionSchedule, $values);
628 return $actionSchedule;
637 * ID of the Reminder to be deleted.
641 public static function del($id) {
643 $dao = new CRM_Core_DAO_ActionSchedule();
645 if ($dao->find(TRUE)) {
650 CRM_Core_Error
::fatal(ts('Invalid value passed to delete function.'));
654 * Update the is_active flag in the db
657 * Id of the database record.
658 * @param bool $is_active
659 * Value we want to set the is_active field.
662 * DAO object on success, null otherwise
665 public static function setIsActive($id, $is_active) {
666 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
670 * @param int $mappingID
673 * @throws CRM_Core_Exception
675 public static function sendMailings($mappingID, $now) {
676 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
677 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
679 $mapping = new CRM_Core_DAO_ActionMapping();
680 $mapping->id
= $mappingID;
681 $mapping->find(TRUE);
683 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
684 $actionSchedule->mapping_id
= $mappingID;
685 $actionSchedule->is_active
= 1;
686 $actionSchedule->find(FALSE);
688 $tokenFields = array();
689 $session = CRM_Core_Session
::singleton();
691 while ($actionSchedule->fetch()) {
692 $extraSelect = $extraJoin = $extraWhere = $extraOn = '';
694 if ($actionSchedule->from_email
) {
695 $fromEmailAddress = "$actionSchedule->from_name <$actionSchedule->from_email>";
698 $activityTypeID = FALSE;
699 $activityStatusID = FALSE;
700 if ($actionSchedule->record_activity
) {
701 if ($mapping->entity
== 'civicrm_membership') {
703 CRM_Core_OptionGroup
::getValue('activity_type', 'Membership Renewal Reminder', 'name');
707 CRM_Core_OptionGroup
::getValue('activity_type', 'Reminder Sent', 'name');
711 CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
714 if ($mapping->entity
== 'civicrm_activity') {
715 $compInfo = CRM_Core_Component
::getEnabledComponents();
716 $tokenEntity = 'activity';
717 $tokenFields = array('activity_id', 'activity_type', 'subject', 'details', 'activity_date_time');
718 $extraSelect = ', ov.label as activity_type, e.id as activity_id';
720 INNER JOIN civicrm_option_group og ON og.name = 'activity_type'
721 INNER JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
722 $extraOn = ' AND e.is_current_revision = 1 AND e.is_deleted = 0 ';
723 if ($actionSchedule->limit_to
== 0) {
725 LEFT JOIN civicrm_option_group og ON og.name = 'activity_type'
726 LEFT JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
730 // if CiviCase component is enabled
731 if (array_key_exists('CiviCase', $compInfo)) {
732 $extraSelect .= ", civicrm_case_activity.case_id as case_id";
734 LEFT JOIN `civicrm_case_activity` ON `e`.`id` = `civicrm_case_activity`.`activity_id`";
738 if ($mapping->entity
== 'civicrm_participant') {
739 $tokenEntity = 'event';
740 $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');
741 $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 ';
744 INNER JOIN civicrm_event ev ON e.event_id = ev.id
745 INNER JOIN civicrm_option_group og ON og.name = 'event_type'
746 INNER JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
747 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
748 LEFT JOIN civicrm_address address ON address.id = lb.address_id
749 LEFT JOIN civicrm_email email ON email.id = lb.email_id
750 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
752 if ($actionSchedule->limit_to
== 0) {
754 LEFT JOIN civicrm_event ev ON e.event_id = ev.id
755 LEFT JOIN civicrm_option_group og ON og.name = 'event_type'
756 LEFT JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
757 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
758 LEFT JOIN civicrm_address address ON address.id = lb.address_id
759 LEFT JOIN civicrm_email email ON email.id = lb.email_id
760 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
765 if ($mapping->entity
== 'civicrm_membership') {
766 $tokenEntity = 'membership';
767 $tokenFields = array('fee', 'id', 'join_date', 'start_date', 'end_date', 'status', 'type');
768 $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';
770 INNER JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
771 INNER JOIN civicrm_membership_status ms ON e.status_id = ms.id';
773 if ($actionSchedule->limit_to
== 0) {
775 LEFT JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
776 LEFT JOIN civicrm_membership_status ms ON e.status_id = ms.id';
780 if ($mapping->entity
== 'civicrm_contact') {
781 $tokenEntity = 'contact';
782 //TODO: get full list somewhere!
783 $tokenFields = array('birth_date', 'last_name');
784 //TODO: is there anything to add here?
787 $entityJoinClause = "INNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
788 if ($actionSchedule->limit_to
== 0) {
789 $entityJoinClause = "LEFT JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
790 $extraWhere .= " AND (e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact')";
792 $entityJoinClause .= $extraOn;
795 SELECT reminder.id as reminderID, reminder.contact_id as contactID, reminder.entity_table as entityTable, reminder.*, e.id as entityID, e.* {$extraSelect}
796 FROM civicrm_action_log reminder
799 WHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL
802 $dao = CRM_Core_DAO
::executeQuery($query,
803 array(1 => array($actionSchedule->id
, 'Integer'))
806 while ($dao->fetch()) {
807 $entityTokenParams = array();
808 foreach ($tokenFields as $field) {
809 if ($field == 'location') {
811 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
812 $loc['street_address'] = $dao->street_address
;
813 $loc['city'] = $dao->city
;
814 $loc['state_province'] = CRM_Utils_Array
::value($dao->state_province_id
, $stateProvince);
815 $loc['postal_code'] = $dao->postal_code
;
816 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address
::format($loc);
818 elseif ($field == 'info_url') {
819 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
821 elseif ($field == 'registration_url') {
822 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
824 elseif (in_array($field, array('start_date', 'end_date', 'join_date', 'activity_date_time'))) {
825 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date
::customFormat($dao->$field);
827 elseif ($field == 'balance') {
828 if ($dao->entityTable
== 'civicrm_contact') {
831 elseif (!empty($dao->entityID
)) {
832 $info = CRM_Contribute_BAO_Contribution
::getPaymentInfo($dao->entityID
, 'event');
833 $balancePay = CRM_Utils_Array
::value('balance', $info);
834 $balancePay = CRM_Utils_Money
::format($balancePay);
836 $entityTokenParams["{$tokenEntity}." . $field] = $balancePay;
838 elseif ($field == 'fee_amount') {
839 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Money
::format($dao->$field);
842 $entityTokenParams["{$tokenEntity}." . $field] = $dao->$field;
847 $errorMsg = $toEmail = $toPhoneNumber = '';
849 if ($actionSchedule->mode
== 'SMS' or $actionSchedule->mode
== 'User_Preference') {
850 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
851 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($dao->contactID
, FALSE, 'Mobile', $filters);
852 //to get primary mobile ph,if not get a first mobile phONE
853 if (!empty($toPhoneNumbers)) {
854 $toPhoneNumberDetails = reset($toPhoneNumbers);
855 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumberDetails);
856 //contact allows to send sms
860 if ($actionSchedule->mode
== 'Email' or $actionSchedule->mode
== 'User_Preference') {
861 $toEmail = CRM_Contact_BAO_Contact
::getPrimaryEmail($dao->contactID
);
863 if ($toEmail ||
!(empty($toPhoneNumber) or $toDoNotSms)) {
864 $to['email'] = $toEmail;
865 $to['phone'] = $toPhoneNumber;
867 CRM_Core_BAO_ActionSchedule
::sendReminder(
875 if (!$result ||
is_a($result, 'PEAR_Error')) {
876 // we could not send an email, for now we ignore, CRM-3406
882 $errorMsg = "Couldn\'t find recipient\'s email address.";
885 // update action log record
887 'id' => $dao->reminderID
,
888 'is_error' => $isError,
889 'message' => $errorMsg ?
$errorMsg : "null",
890 'action_date_time' => $now,
892 CRM_Core_BAO_ActionLog
::create($logParams);
894 // insert activity log record if needed
895 if ($actionSchedule->record_activity
&& !$isError) {
896 $activityParams = array(
897 'subject' => $actionSchedule->title
,
898 'details' => $actionSchedule->body_html
,
899 'source_contact_id' =>
900 $session->get('userID') ?
$session->get('userID') : $dao->contactID
,
901 'target_contact_id' => $dao->contactID
,
902 'activity_date_time' => date('YmdHis'),
903 'status_id' => $activityStatusID,
904 'activity_type_id' => $activityTypeID,
905 'source_record_id' => $dao->entityID
,
907 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
909 //file reminder on case if source activity is a case activity
910 if (!empty($dao->case_id
)) {
911 $caseActivityParams = array();
912 $caseActivityParams['case_id'] = $dao->case_id
;
913 $caseActivityParams['activity_id'] = $activity->id
;
914 CRM_Case_BAO_Case
::processCaseActivity($caseActivityParams);
924 * @param int $mappingID
926 * @param array $params
928 * @throws API_Exception
930 public static function buildRecipientContacts($mappingID, $now, $params = array()) {
931 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
932 $actionSchedule->mapping_id
= $mappingID;
933 $actionSchedule->is_active
= 1;
934 if (!empty($params)) {
935 _civicrm_api3_dao_set_filter($actionSchedule, $params, FALSE, 'ActionSchedule');
937 $actionSchedule->find();
939 while ($actionSchedule->fetch()) {
940 $mapping = new CRM_Core_DAO_ActionMapping();
941 $mapping->id
= $mappingID;
942 $mapping->find(TRUE);
944 // note: $where - this filtering applies for both
945 // 'limit to' and 'addition to' options
946 // $limitWhere - this filtering applies only for
948 $select = $join = $where = $limitWhere = array();
949 $limitTo = $actionSchedule->limit_to
;
950 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
951 trim($actionSchedule->entity_value
, CRM_Core_DAO
::VALUE_SEPARATOR
)
953 $value = implode(',', $value);
955 $status = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
956 trim($actionSchedule->entity_status
, CRM_Core_DAO
::VALUE_SEPARATOR
)
958 $status = implode(',', $status);
960 $anniversary = FALSE;
962 if (!CRM_Utils_System
::isNull($mapping->entity_recipient
)) {
963 if ($mapping->entity_recipient
== 'event_contacts') {
964 $recipientOptions = CRM_Core_OptionGroup
::values($mapping->entity_recipient
, FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
967 $recipientOptions = CRM_Core_OptionGroup
::values($mapping->entity_recipient
, FALSE, FALSE, FALSE, NULL, 'name');
970 $from = "{$mapping->entity} e";
972 if ($mapping->entity
== 'civicrm_activity') {
973 $contactField = 'r.contact_id';
974 $table = 'civicrm_activity e';
975 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
976 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
977 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
978 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
980 if (!is_null($limitTo)) {
982 // including the activity target contacts if 'in addition' is defined
983 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
986 switch (CRM_Utils_Array
::value($actionSchedule->recipient
, $recipientOptions)) {
987 case 'Activity Assignees':
988 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$assigneeID}";
991 case 'Activity Source':
992 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$sourceID}";
996 case 'Activity Targets':
997 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
1002 // build where clause
1003 if (!empty($value)) {
1004 $where[] = "e.activity_type_id IN ({$value})";
1007 $where[] = "e.activity_type_id IS NULL";
1009 if (!empty($status)) {
1010 $where[] = "e.status_id IN ({$status})";
1012 $where[] = ' e.is_current_revision = 1 ';
1013 $where[] = ' e.is_deleted = 0 ';
1015 $dateField = 'e.activity_date_time';
1018 if ($mapping->entity
== 'civicrm_participant') {
1019 $table = 'civicrm_event r';
1020 $contactField = 'e.contact_id';
1021 $join[] = 'INNER JOIN civicrm_event r ON e.event_id = r.id';
1022 if ($actionSchedule->recipient_listing
&& $limitTo) {
1023 $rList = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1024 trim($actionSchedule->recipient_listing
, CRM_Core_DAO
::VALUE_SEPARATOR
)
1026 $rList = implode(',', $rList);
1028 switch ($recipientOptions[$actionSchedule->recipient
]) {
1029 case 'participant_role':
1030 $where[] = "e.role_id IN ({$rList})";
1038 // build where clause
1039 if (!empty($value)) {
1040 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IN ({$value})" : "r.id IN ({$value})";
1043 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IS NULL" : "r.id IS NULL";
1046 // participant status criteria not to be implemented
1047 // for additional recipients
1048 if (!empty($status)) {
1049 $limitWhere[] = "e.status_id IN ({$status})";
1052 $where[] = 'r.is_active = 1';
1053 $where[] = 'r.is_template = 0';
1054 $dateField = str_replace('event_', 'r.', $actionSchedule->start_action_date
);
1058 if ($mapping->entity
== 'civicrm_membership') {
1059 $contactField = 'e.contact_id';
1060 $table = 'civicrm_membership e';
1061 // build where clause
1063 //auto-renew memberships
1064 $where[] = "e.contribution_recur_id IS NOT NULL ";
1066 elseif ($status == 1) {
1067 $where[] = "e.contribution_recur_id IS NULL ";
1070 // build where clause
1071 if (!empty($value)) {
1072 $where[] = "e.membership_type_id IN ({$value})";
1075 $where[] = "e.membership_type_id IS NULL";
1078 $where[] = "( e.is_override IS NULL OR e.is_override = 0 )";
1079 $dateField = str_replace('membership_', 'e.', $actionSchedule->start_action_date
);
1080 $notINClause = self
::permissionedRelationships($contactField);
1082 $membershipStatus = CRM_Member_PseudoConstant
::membershipStatus(NULL, "(is_current_member = 1 OR name = 'Expired')", 'id');
1083 $mStatus = implode(',', $membershipStatus);
1084 $where[] = "e.status_id IN ({$mStatus})";
1087 if ($mapping->entity
== 'civicrm_contact') {
1088 if ($value == 'birth_date') {
1089 $dateDBField = 'birth_date';
1090 $table = 'civicrm_contact e';
1091 $contactField = 'e.id';
1092 $where[] = 'e.is_deleted = 0';
1093 $where[] = 'e.is_deceased = 0';
1097 $customFieldParams = array('id' => substr($value, 7));
1098 $customGroup = $customField = array();
1099 CRM_Core_BAO_CustomField
::retrieve($customFieldParams, $customField);
1100 $dateDBField = $customField['column_name'];
1101 $customGroupParams = array('id' => $customField['custom_group_id'], $customGroup);
1102 CRM_Core_BAO_CustomGroup
::retrieve($customGroupParams, $customGroup);
1103 $from = $table = "{$customGroup['table_name']} e";
1104 $contactField = 'e.entity_id';
1105 $where[] = '1'; // possible to have no "where" in this case
1108 $status_ = explode(',', $status);
1109 if (in_array(2, $status_)) {
1110 // anniversary mode:
1111 $dateField = 'DATE_ADD(e.' . $dateDBField . ', INTERVAL ROUND(DATEDIFF(DATE(' . $now . '), e.' . $dateDBField . ') / 365) YEAR)';
1112 $anniversary = TRUE;
1116 $dateField = 'e.' . $dateDBField;
1118 // TODO get this working
1120 // TODO: Make sure everything's provided for repetition, etc.
1123 // CRM-13577 Introduce Smart Groups Handling
1124 if ($actionSchedule->group_id
) {
1126 // Need to check if its a smart group or not
1127 // Then decide which table to join onto the query
1128 $group = CRM_Contact_DAO_Group
::getTableName();
1130 // Get the group information
1132 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
1134 WHERE $group.id = {$actionSchedule->group_id}
1137 $groupDAO = CRM_Core_DAO
::executeQuery($sql);
1138 $isSmartGroup = FALSE;
1140 $groupDAO->fetch() &&
1141 !empty($groupDAO->saved_search_id
)
1143 // Check that the group is in place in the cache and up to date
1144 CRM_Contact_BAO_GroupContactCache
::check($actionSchedule->group_id
);
1145 // Set smart group flag
1146 $isSmartGroup = TRUE;
1149 // CRM-13577 End Introduce Smart Groups Handling
1152 if ($actionSchedule->group_id
) {
1153 // CRM-13577 If smart group then use Cache table
1154 if ($isSmartGroup) {
1155 $join[] = "INNER JOIN civicrm_group_contact_cache grp ON {$contactField} = grp.contact_id";
1156 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1159 $join[] = "INNER JOIN civicrm_group_contact grp ON {$contactField} = grp.contact_id AND grp.status = 'Added'";
1160 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1163 elseif (!empty($actionSchedule->recipient_manual
)) {
1164 $rList = CRM_Utils_Type
::escape($actionSchedule->recipient_manual
, 'String');
1165 $where[] = "{$contactField} IN ({$rList})";
1168 elseif (!is_null($limitTo)) {
1169 $addGroup = $addWhere = '';
1170 if ($actionSchedule->group_id
) {
1171 // CRM-13577 If smart group then use Cache table
1172 if ($isSmartGroup) {
1173 $addGroup = " INNER JOIN civicrm_group_contact_cache grp ON c.id = grp.contact_id";
1174 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1177 $addGroup = " INNER JOIN civicrm_group_contact grp ON c.id = grp.contact_id AND grp.status = 'Added'";
1178 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1181 if (!empty($actionSchedule->recipient_manual
)) {
1182 $rList = CRM_Utils_Type
::escape($actionSchedule->recipient_manual
, 'String');
1183 $addWhere = "c.id IN ({$rList})";
1187 $select[] = "{$contactField} as contact_id";
1188 $select[] = 'e.id as entity_id';
1189 $select[] = "'{$mapping->entity}' as entity_table";
1190 $select[] = "{$actionSchedule->id} as action_schedule_id";
1191 $reminderJoinClause = "civicrm_action_log reminder ON reminder.contact_id = {$contactField} AND
1192 reminder.entity_id = e.id AND
1193 reminder.entity_table = '{$mapping->entity}' AND
1194 reminder.action_schedule_id = %1";
1197 // only consider reminders less than 11 months ago
1198 $reminderJoinClause .= " AND reminder.action_date_time > DATE_SUB({$now}, INTERVAL 11 MONTH)";
1201 if ($table != 'civicrm_contact e') {
1202 $join[] = "INNER JOIN civicrm_contact c ON c.id = {$contactField} AND c.is_deleted = 0 AND c.is_deceased = 0 ";
1205 if ($actionSchedule->start_action_date
) {
1206 $startDateClause = array();
1207 $op = ($actionSchedule->start_action_condition
== 'before' ?
'<=' : '>=');
1208 $operator = ($actionSchedule->start_action_condition
== 'before' ?
'DATE_SUB' : 'DATE_ADD');
1209 $date = $operator . "({$dateField}, INTERVAL {$actionSchedule->start_action_offset} {$actionSchedule->start_action_unit})";
1210 $startDateClause[] = "'{$now}' >= {$date}";
1211 if ($mapping->entity
== 'civicrm_participant') {
1212 $startDateClause[] = $operator . "({$now}, INTERVAL 1 DAY ) {$op} " . $dateField;
1215 $startDateClause[] = "DATE_SUB({$now}, INTERVAL 1 DAY ) <= {$date}";
1218 $startDate = implode(' AND ', $startDateClause);
1220 elseif ($actionSchedule->absolute_date
) {
1221 $startDate = "DATEDIFF(DATE('{$now}'),'{$actionSchedule->absolute_date}') = 0";
1224 // ( now >= date_built_from_start_time ) OR ( now = absolute_date )
1225 $dateClause = "reminder.id IS NULL AND {$startDate}";
1227 // start composing query
1228 $selectClause = 'SELECT ' . implode(', ', $select);
1229 $fromClause = "FROM $from";
1230 $joinClause = !empty($join) ?
implode(' ', $join) : '';
1231 $whereClause = 'WHERE ' . implode(' AND ', $where);
1232 $limitWhereClause = '';
1233 if (!empty($limitWhere)) {
1234 $limitWhereClause = ' AND ' . implode(' AND ', $limitWhere);
1238 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1242 LEFT JOIN {$reminderJoinClause}
1243 {$whereClause} {$limitWhereClause} AND {$dateClause} {$notINClause}
1245 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
1246 $isSendToAdditionalContacts = (!is_null($limitTo) && $limitTo == 0 && (!empty($addGroup) ||
!empty($addWhere))) ?
TRUE : FALSE;
1247 if ($isSendToAdditionalContacts) {
1248 $contactTable = "civicrm_contact c";
1249 $addSelect = "SELECT c.id as contact_id, c.id as entity_id, 'civicrm_contact' as entity_table, {$actionSchedule->id} as action_schedule_id";
1250 $additionReminderClause = "civicrm_action_log reminder ON reminder.contact_id = c.id AND
1251 reminder.entity_id = c.id AND
1252 reminder.entity_table = 'civicrm_contact' AND
1253 reminder.action_schedule_id = {$actionSchedule->id}";
1254 $addWhereClause = '';
1256 $addWhereClause = "AND {$addWhere}";
1258 $insertAdditionalSql = "
1259 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1261 FROM ({$contactTable})
1262 LEFT JOIN {$additionReminderClause}
1264 WHERE c.is_deleted = 0 AND c.is_deceased = 0
1268 SELECT rem.contact_id
1269 FROM civicrm_action_log rem INNER JOIN {$mapping->entity} e ON rem.entity_id = e.id
1270 WHERE rem.action_schedule_id = {$actionSchedule->id}
1271 AND rem.entity_table = '{$mapping->entity}'
1275 CRM_Core_DAO
::executeQuery($insertAdditionalSql);
1277 // if repeat is turned ON:
1278 if ($actionSchedule->is_repeat
) {
1279 $repeatEvent = ($actionSchedule->end_action
== 'before' ?
'DATE_SUB' : 'DATE_ADD') . "({$dateField}, INTERVAL {$actionSchedule->end_frequency_interval} {$actionSchedule->end_frequency_unit})";
1281 if ($actionSchedule->repetition_frequency_unit
== 'day') {
1282 $hrs = 24 * $actionSchedule->repetition_frequency_interval
;
1284 elseif ($actionSchedule->repetition_frequency_unit
== 'week') {
1285 $hrs = 24 * $actionSchedule->repetition_frequency_interval
* 7;
1287 elseif ($actionSchedule->repetition_frequency_unit
== 'month') {
1288 $hrs = "24*(DATEDIFF(DATE_ADD(latest_log_time, INTERVAL 1 MONTH ), latest_log_time))";
1290 elseif ($actionSchedule->repetition_frequency_unit
== 'year') {
1291 $hrs = "24*(DATEDIFF(DATE_ADD(latest_log_time, INTERVAL 1 YEAR ), latest_log_time))";
1294 $hrs = $actionSchedule->repetition_frequency_interval
;
1297 // (now <= repeat_end_time )
1298 $repeatEventClause = "'{$now}' <= {$repeatEvent}";
1299 // diff(now && logged_date_time) >= repeat_interval
1300 $havingClause = "HAVING TIMEDIFF({$now}, latest_log_time) >= TIME('{$hrs}:00:00')";
1301 $groupByClause = 'GROUP BY reminder.contact_id, reminder.entity_id, reminder.entity_table';
1302 $selectClause .= ', MAX(reminder.action_date_time) as latest_log_time';
1303 //CRM-15376 - do not send our reminders if original criteria no longer applies
1304 // the first part of the startDateClause array is the earliest the reminder can be sent. If the
1305 // event (e.g membership_end_date) has changed then the reminder may no longer apply
1306 // @todo - this only handles events that get moved later. Potentially they might get moved earlier
1307 $originalEventStartDateClause = empty($startDateClause) ?
'' : 'AND' . $startDateClause[0];
1308 $sqlInsertValues = "{$selectClause}
1311 INNER JOIN {$reminderJoinClause}
1312 {$whereClause} {$limitWhereClause} AND {$repeatEventClause} {$originalEventStartDateClause} {$notINClause}
1316 $valsqlInsertValues = CRM_Core_DAO
::executeQuery($sqlInsertValues, array(1 => array($actionSchedule->id
, 'Integer')));
1318 $arrValues = array();
1319 while ($valsqlInsertValues->fetch()) {
1320 $arrValues[] = "( {$valsqlInsertValues->contact_id}, {$valsqlInsertValues->entity_id}, '{$valsqlInsertValues->entity_table}',{$valsqlInsertValues->action_schedule_id} )";
1323 $valString = implode(',', $arrValues);
1327 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1328 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
1331 if ($isSendToAdditionalContacts) {
1332 $addSelect .= ', MAX(reminder.action_date_time) as latest_log_time';
1333 $sqlEndEventCheck = "
1334 SELECT * FROM {$table}
1335 {$whereClause} AND {$repeatEventClause} LIMIT 1";
1337 $daoCheck = CRM_Core_DAO
::executeQuery($sqlEndEventCheck);
1338 if ($daoCheck->fetch()) {
1339 $valSqlAdditionInsert = "
1341 FROM {$contactTable}
1343 INNER JOIN {$additionReminderClause}
1344 WHERE {$addWhere} AND c.is_deleted = 0 AND c.is_deceased = 0
1345 GROUP BY reminder.contact_id
1348 $daoForVals = CRM_Core_DAO
::executeQuery($valSqlAdditionInsert);
1349 $addValues = array();
1350 while ($daoForVals->fetch()) {
1351 $addValues[] = "( {$daoForVals->contact_id}, {$daoForVals->entity_id}, '{$daoForVals->entity_table}',{$daoForVals->action_schedule_id} )";
1353 $valString = implode(',', $addValues);
1357 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1358 CRM_Core_DAO
::executeQuery($query);
1369 * @return null|string
1371 public static function permissionedRelationships($field) {
1373 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
1374 FROM civicrm_membership m
1375 LEFT JOIN civicrm_membership cm ON cm.id = m.owner_membership_id
1376 LEFT JOIN civicrm_membership_type cmt ON cmt.id = m.membership_type_id
1377 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 )
1378 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 ) )
1379 WHERE m.owner_membership_id IS NOT NULL AND
1380 ( rel.is_permission_a_b = 0 OR rel.is_permission_b_a = 0)
1383 $excludeIds = array();
1384 $dao = CRM_Core_DAO
::executeQuery($query, array());
1385 while ($dao->fetch()) {
1386 if ($dao->slave_contact
== $dao->contact_id_a
&& $dao->is_permission_a_b
== 0) {
1387 $excludeIds[] = $dao->slave_contact
;
1389 elseif ($dao->slave_contact
== $dao->contact_id_b
&& $dao->is_permission_b_a
== 0) {
1390 $excludeIds[] = $dao->slave_contact
;
1394 if (!empty($excludeIds)) {
1395 $clause = "AND {$field} NOT IN ( " . implode(', ', $excludeIds) . ' ) ';
1403 * @param array $params
1407 public static function processQueue($now = NULL, $params = array()) {
1408 $now = $now ? CRM_Utils_Time
::setTime($now) : CRM_Utils_Time
::getTime();
1410 $mappings = self
::getMapping();
1411 foreach ($mappings as $mappingID => $mapping) {
1412 self
::buildRecipientContacts($mappingID, $now, $params);
1413 self
::sendMailings($mappingID, $now);
1418 'messages' => ts('Sent all scheduled reminders successfully'),
1425 * @param int $mappingID
1427 * @return null|string
1429 public static function isConfigured($id, $mappingID) {
1430 $queryString = "SELECT count(id) FROM civicrm_action_schedule
1431 WHERE mapping_id = %1 AND
1435 1 => array($mappingID, 'Integer'),
1436 2 => array($id, 'Integer'),
1438 return CRM_Core_DAO
::singleValueQuery($queryString, $params);
1442 * @param int $mappingID
1443 * @param $recipientType
1447 public static function getRecipientListing($mappingID, $recipientType) {
1449 if (!$mappingID ||
!$recipientType) {
1453 $mapping = self
::getMapping($mappingID);
1455 switch ($mapping['entity']) {
1456 case 'civicrm_participant':
1457 $eventContacts = CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
1458 if (empty($eventContacts[$recipientType])) {
1461 if ($eventContacts[$recipientType] == 'participant_role') {
1462 $options = CRM_Event_PseudoConstant
::participantRole();