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
596 public static function add(&$params, $ids = array()) {
597 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
598 $actionSchedule->copyValues($params);
600 return $actionSchedule->save();
604 * Takes a bunch of params that are needed to match certain criteria and
605 * retrieves the relevant objects. It also stores all the retrieved
606 * values in the default array
608 * @param array $params
609 * (reference ) an assoc array of name/value pairs.
610 * @param array $values
611 * (reference ) an assoc array to hold the flattened values.
613 * @return CRM_Core_DAO_ActionSchedule object on success, null otherwise
616 public static function retrieve(&$params, &$values) {
617 if (empty($params)) {
620 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
622 $actionSchedule->copyValues($params);
624 if ($actionSchedule->find(TRUE)) {
625 $ids['actionSchedule'] = $actionSchedule->id
;
627 CRM_Core_DAO
::storeValues($actionSchedule, $values);
629 return $actionSchedule;
638 * ID of the Reminder to be deleted.
642 public static function del($id) {
644 $dao = new CRM_Core_DAO_ActionSchedule();
646 if ($dao->find(TRUE)) {
651 CRM_Core_Error
::fatal(ts('Invalid value passed to delete function.'));
655 * Update the is_active flag in the db
658 * Id of the database record.
659 * @param bool $is_active
660 * Value we want to set the is_active field.
663 * DAO object on success, null otherwise
666 public static function setIsActive($id, $is_active) {
667 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
671 * @param int $mappingID
674 * @throws CRM_Core_Exception
676 public static function sendMailings($mappingID, $now) {
677 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
678 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
680 $mapping = new CRM_Core_DAO_ActionMapping();
681 $mapping->id
= $mappingID;
682 $mapping->find(TRUE);
684 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
685 $actionSchedule->mapping_id
= $mappingID;
686 $actionSchedule->is_active
= 1;
687 $actionSchedule->find(FALSE);
689 $tokenFields = array();
690 $session = CRM_Core_Session
::singleton();
692 while ($actionSchedule->fetch()) {
693 $extraSelect = $extraJoin = $extraWhere = $extraOn = '';
695 if ($actionSchedule->from_email
) {
696 $fromEmailAddress = "$actionSchedule->from_name <$actionSchedule->from_email>";
699 $activityTypeID = FALSE;
700 $activityStatusID = FALSE;
701 if ($actionSchedule->record_activity
) {
702 if ($mapping->entity
== 'civicrm_membership') {
704 CRM_Core_OptionGroup
::getValue('activity_type', 'Membership Renewal Reminder', 'name');
708 CRM_Core_OptionGroup
::getValue('activity_type', 'Reminder Sent', 'name');
712 CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
715 if ($mapping->entity
== 'civicrm_activity') {
716 $compInfo = CRM_Core_Component
::getEnabledComponents();
717 $tokenEntity = 'activity';
718 $tokenFields = array('activity_id', 'activity_type', 'subject', 'details', 'activity_date_time');
719 $extraSelect = ', ov.label as activity_type, e.id as activity_id';
721 INNER JOIN civicrm_option_group og ON og.name = 'activity_type'
722 INNER JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
723 $extraOn = ' AND e.is_current_revision = 1 AND e.is_deleted = 0 ';
724 if ($actionSchedule->limit_to
== 0) {
726 LEFT JOIN civicrm_option_group og ON og.name = 'activity_type'
727 LEFT JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
731 // if CiviCase component is enabled
732 if (array_key_exists('CiviCase', $compInfo)) {
733 $extraSelect .= ", civicrm_case_activity.case_id as case_id";
735 LEFT JOIN `civicrm_case_activity` ON `e`.`id` = `civicrm_case_activity`.`activity_id`";
739 if ($mapping->entity
== 'civicrm_participant') {
740 $tokenEntity = 'event';
741 $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');
742 $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 ';
745 INNER JOIN civicrm_event ev ON e.event_id = ev.id
746 INNER JOIN civicrm_option_group og ON og.name = 'event_type'
747 INNER JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
748 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
749 LEFT JOIN civicrm_address address ON address.id = lb.address_id
750 LEFT JOIN civicrm_email email ON email.id = lb.email_id
751 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
753 if ($actionSchedule->limit_to
== 0) {
755 LEFT JOIN civicrm_event ev ON e.event_id = ev.id
756 LEFT JOIN civicrm_option_group og ON og.name = 'event_type'
757 LEFT JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
758 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
759 LEFT JOIN civicrm_address address ON address.id = lb.address_id
760 LEFT JOIN civicrm_email email ON email.id = lb.email_id
761 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
766 if ($mapping->entity
== 'civicrm_membership') {
767 $tokenEntity = 'membership';
768 $tokenFields = array('fee', 'id', 'join_date', 'start_date', 'end_date', 'status', 'type');
769 $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';
771 INNER JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
772 INNER JOIN civicrm_membership_status ms ON e.status_id = ms.id';
774 if ($actionSchedule->limit_to
== 0) {
776 LEFT JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
777 LEFT JOIN civicrm_membership_status ms ON e.status_id = ms.id';
781 if ($mapping->entity
== 'civicrm_contact') {
782 $tokenEntity = 'contact';
783 //TODO: get full list somewhere!
784 $tokenFields = array('birth_date', 'last_name');
785 //TODO: is there anything to add here?
788 $entityJoinClause = "INNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
789 if ($actionSchedule->limit_to
== 0) {
790 $entityJoinClause = "LEFT JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
791 $extraWhere .= " AND (e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact')";
793 $entityJoinClause .= $extraOn;
796 SELECT reminder.id as reminderID, reminder.contact_id as contactID, reminder.entity_table as entityTable, reminder.*, e.id as entityID, e.* {$extraSelect}
797 FROM civicrm_action_log reminder
800 WHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL
803 $dao = CRM_Core_DAO
::executeQuery($query,
804 array(1 => array($actionSchedule->id
, 'Integer'))
807 while ($dao->fetch()) {
808 $entityTokenParams = array();
809 foreach ($tokenFields as $field) {
810 if ($field == 'location') {
812 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
813 $loc['street_address'] = $dao->street_address
;
814 $loc['city'] = $dao->city
;
815 $loc['state_province'] = CRM_Utils_Array
::value($dao->state_province_id
, $stateProvince);
816 $loc['postal_code'] = $dao->postal_code
;
817 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address
::format($loc);
819 elseif ($field == 'info_url') {
820 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
822 elseif ($field == 'registration_url') {
823 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
825 elseif (in_array($field, array('start_date', 'end_date', 'join_date', 'activity_date_time'))) {
826 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date
::customFormat($dao->$field);
828 elseif ($field == 'balance') {
829 if ($dao->entityTable
== 'civicrm_contact') {
832 elseif (!empty($dao->entityID
)) {
833 $info = CRM_Contribute_BAO_Contribution
::getPaymentInfo($dao->entityID
, 'event');
834 $balancePay = CRM_Utils_Array
::value('balance', $info);
835 $balancePay = CRM_Utils_Money
::format($balancePay);
837 $entityTokenParams["{$tokenEntity}." . $field] = $balancePay;
839 elseif ($field == 'fee_amount') {
840 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Money
::format($dao->$field);
843 $entityTokenParams["{$tokenEntity}." . $field] = $dao->$field;
848 $errorMsg = $toEmail = $toPhoneNumber = '';
850 if ($actionSchedule->mode
== 'SMS' or $actionSchedule->mode
== 'User_Preference') {
851 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
852 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($dao->contactID
, FALSE, 'Mobile', $filters);
853 //to get primary mobile ph,if not get a first mobile phONE
854 if (!empty($toPhoneNumbers)) {
855 $toPhoneNumberDetails = reset($toPhoneNumbers);
856 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumberDetails);
857 //contact allows to send sms
861 if ($actionSchedule->mode
== 'Email' or $actionSchedule->mode
== 'User_Preference') {
862 $toEmail = CRM_Contact_BAO_Contact
::getPrimaryEmail($dao->contactID
);
864 if ($toEmail ||
!(empty($toPhoneNumber) or $toDoNotSms)) {
865 $to['email'] = $toEmail;
866 $to['phone'] = $toPhoneNumber;
868 CRM_Core_BAO_ActionSchedule
::sendReminder(
876 if (!$result ||
is_a($result, 'PEAR_Error')) {
877 // we could not send an email, for now we ignore, CRM-3406
883 $errorMsg = "Couldn\'t find recipient\'s email address.";
886 // update action log record
888 'id' => $dao->reminderID
,
889 'is_error' => $isError,
890 'message' => $errorMsg ?
$errorMsg : "null",
891 'action_date_time' => $now,
893 CRM_Core_BAO_ActionLog
::create($logParams);
895 // insert activity log record if needed
896 if ($actionSchedule->record_activity
&& !$isError) {
897 $activityParams = array(
898 'subject' => $actionSchedule->title
,
899 'details' => $actionSchedule->body_html
,
900 'source_contact_id' =>
901 $session->get('userID') ?
$session->get('userID') : $dao->contactID
,
902 'target_contact_id' => $dao->contactID
,
903 'activity_date_time' => date('YmdHis'),
904 'status_id' => $activityStatusID,
905 'activity_type_id' => $activityTypeID,
906 'source_record_id' => $dao->entityID
,
908 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
910 //file reminder on case if source activity is a case activity
911 if (!empty($dao->case_id
)) {
912 $caseActivityParams = array();
913 $caseActivityParams['case_id'] = $dao->case_id
;
914 $caseActivityParams['activity_id'] = $activity->id
;
915 CRM_Case_BAO_Case
::processCaseActivity($caseActivityParams);
925 * @param int $mappingID
927 * @param array $params
929 * @throws API_Exception
931 public static function buildRecipientContacts($mappingID, $now, $params = array()) {
932 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
933 $actionSchedule->mapping_id
= $mappingID;
934 $actionSchedule->is_active
= 1;
935 if (!empty($params)) {
936 _civicrm_api3_dao_set_filter($actionSchedule, $params, FALSE, 'ActionSchedule');
938 $actionSchedule->find();
940 while ($actionSchedule->fetch()) {
941 $mapping = new CRM_Core_DAO_ActionMapping();
942 $mapping->id
= $mappingID;
943 $mapping->find(TRUE);
945 // note: $where - this filtering applies for both
946 // 'limit to' and 'addition to' options
947 // $limitWhere - this filtering applies only for
949 $select = $join = $where = $limitWhere = array();
950 $limitTo = $actionSchedule->limit_to
;
951 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
952 trim($actionSchedule->entity_value
, CRM_Core_DAO
::VALUE_SEPARATOR
)
954 $value = implode(',', $value);
956 $status = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
957 trim($actionSchedule->entity_status
, CRM_Core_DAO
::VALUE_SEPARATOR
)
959 $status = implode(',', $status);
961 $anniversary = FALSE;
963 if (!CRM_Utils_System
::isNull($mapping->entity_recipient
)) {
964 if ($mapping->entity_recipient
== 'event_contacts') {
965 $recipientOptions = CRM_Core_OptionGroup
::values($mapping->entity_recipient
, FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
968 $recipientOptions = CRM_Core_OptionGroup
::values($mapping->entity_recipient
, FALSE, FALSE, FALSE, NULL, 'name');
971 $from = "{$mapping->entity} e";
973 if ($mapping->entity
== 'civicrm_activity') {
974 $contactField = 'r.contact_id';
975 $table = 'civicrm_activity e';
976 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
977 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
978 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
979 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
981 if (!is_null($limitTo)) {
983 // including the activity target contacts if 'in addition' is defined
984 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
987 switch (CRM_Utils_Array
::value($actionSchedule->recipient
, $recipientOptions)) {
988 case 'Activity Assignees':
989 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$assigneeID}";
992 case 'Activity Source':
993 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$sourceID}";
997 case 'Activity Targets':
998 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
1003 // build where clause
1004 if (!empty($value)) {
1005 $where[] = "e.activity_type_id IN ({$value})";
1008 $where[] = "e.activity_type_id IS NULL";
1010 if (!empty($status)) {
1011 $where[] = "e.status_id IN ({$status})";
1013 $where[] = ' e.is_current_revision = 1 ';
1014 $where[] = ' e.is_deleted = 0 ';
1016 $dateField = 'e.activity_date_time';
1019 if ($mapping->entity
== 'civicrm_participant') {
1020 $table = 'civicrm_event r';
1021 $contactField = 'e.contact_id';
1022 $join[] = 'INNER JOIN civicrm_event r ON e.event_id = r.id';
1023 if ($actionSchedule->recipient_listing
&& $limitTo) {
1024 $rList = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1025 trim($actionSchedule->recipient_listing
, CRM_Core_DAO
::VALUE_SEPARATOR
)
1027 $rList = implode(',', $rList);
1029 switch ($recipientOptions[$actionSchedule->recipient
]) {
1030 case 'participant_role':
1031 $where[] = "e.role_id IN ({$rList})";
1039 // build where clause
1040 if (!empty($value)) {
1041 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IN ({$value})" : "r.id IN ({$value})";
1044 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IS NULL" : "r.id IS NULL";
1047 // participant status criteria not to be implemented
1048 // for additional recipients
1049 if (!empty($status)) {
1050 $limitWhere[] = "e.status_id IN ({$status})";
1053 $where[] = 'r.is_active = 1';
1054 $where[] = 'r.is_template = 0';
1055 $dateField = str_replace('event_', 'r.', $actionSchedule->start_action_date
);
1059 if ($mapping->entity
== 'civicrm_membership') {
1060 $contactField = 'e.contact_id';
1061 $table = 'civicrm_membership e';
1062 // build where clause
1064 //auto-renew memberships
1065 $where[] = "e.contribution_recur_id IS NOT NULL ";
1067 elseif ($status == 1) {
1068 $where[] = "e.contribution_recur_id IS NULL ";
1071 // build where clause
1072 if (!empty($value)) {
1073 $where[] = "e.membership_type_id IN ({$value})";
1076 $where[] = "e.membership_type_id IS NULL";
1079 $where[] = "( e.is_override IS NULL OR e.is_override = 0 )";
1080 $dateField = str_replace('membership_', 'e.', $actionSchedule->start_action_date
);
1081 $notINClause = self
::permissionedRelationships($contactField);
1083 $membershipStatus = CRM_Member_PseudoConstant
::membershipStatus(NULL, "(is_current_member = 1 OR name = 'Expired')", 'id');
1084 $mStatus = implode(',', $membershipStatus);
1085 $where[] = "e.status_id IN ({$mStatus})";
1088 if ($mapping->entity
== 'civicrm_contact') {
1089 if ($value == 'birth_date') {
1090 $dateDBField = 'birth_date';
1091 $table = 'civicrm_contact e';
1092 $contactField = 'e.id';
1093 $where[] = 'e.is_deleted = 0';
1094 $where[] = 'e.is_deceased = 0';
1098 $customFieldParams = array('id' => substr($value, 7));
1099 $customGroup = $customField = array();
1100 CRM_Core_BAO_CustomField
::retrieve($customFieldParams, $customField);
1101 $dateDBField = $customField['column_name'];
1102 $customGroupParams = array('id' => $customField['custom_group_id'], $customGroup);
1103 CRM_Core_BAO_CustomGroup
::retrieve($customGroupParams, $customGroup);
1104 $from = $table = "{$customGroup['table_name']} e";
1105 $contactField = 'e.entity_id';
1106 $where[] = '1'; // possible to have no "where" in this case
1109 $status_ = explode(',', $status);
1110 if (in_array(2, $status_)) {
1111 // anniversary mode:
1112 $dateField = 'DATE_ADD(e.' . $dateDBField . ', INTERVAL ROUND(DATEDIFF(DATE(' . $now . '), e.' . $dateDBField . ') / 365) YEAR)';
1113 $anniversary = TRUE;
1117 $dateField = 'e.' . $dateDBField;
1119 // TODO get this working
1121 // TODO: Make sure everything's provided for repetition, etc.
1124 // CRM-13577 Introduce Smart Groups Handling
1125 if ($actionSchedule->group_id
) {
1127 // Need to check if its a smart group or not
1128 // Then decide which table to join onto the query
1129 $group = CRM_Contact_DAO_Group
::getTableName();
1131 // Get the group information
1133 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
1135 WHERE $group.id = {$actionSchedule->group_id}
1138 $groupDAO = CRM_Core_DAO
::executeQuery($sql);
1139 $isSmartGroup = FALSE;
1141 $groupDAO->fetch() &&
1142 !empty($groupDAO->saved_search_id
)
1144 // Check that the group is in place in the cache and up to date
1145 CRM_Contact_BAO_GroupContactCache
::check($actionSchedule->group_id
);
1146 // Set smart group flag
1147 $isSmartGroup = TRUE;
1150 // CRM-13577 End Introduce Smart Groups Handling
1153 if ($actionSchedule->group_id
) {
1154 // CRM-13577 If smart group then use Cache table
1155 if ($isSmartGroup) {
1156 $join[] = "INNER JOIN civicrm_group_contact_cache grp ON {$contactField} = grp.contact_id";
1157 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1160 $join[] = "INNER JOIN civicrm_group_contact grp ON {$contactField} = grp.contact_id AND grp.status = 'Added'";
1161 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1164 elseif (!empty($actionSchedule->recipient_manual
)) {
1165 $rList = CRM_Utils_Type
::escape($actionSchedule->recipient_manual
, 'String');
1166 $where[] = "{$contactField} IN ({$rList})";
1169 elseif (!is_null($limitTo)) {
1170 $addGroup = $addWhere = '';
1171 if ($actionSchedule->group_id
) {
1172 // CRM-13577 If smart group then use Cache table
1173 if ($isSmartGroup) {
1174 $addGroup = " INNER JOIN civicrm_group_contact_cache grp ON c.id = grp.contact_id";
1175 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1178 $addGroup = " INNER JOIN civicrm_group_contact grp ON c.id = grp.contact_id AND grp.status = 'Added'";
1179 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1182 if (!empty($actionSchedule->recipient_manual
)) {
1183 $rList = CRM_Utils_Type
::escape($actionSchedule->recipient_manual
, 'String');
1184 $addWhere = "c.id IN ({$rList})";
1188 $select[] = "{$contactField} as contact_id";
1189 $select[] = 'e.id as entity_id';
1190 $select[] = "'{$mapping->entity}' as entity_table";
1191 $select[] = "{$actionSchedule->id} as action_schedule_id";
1192 $reminderJoinClause = "civicrm_action_log reminder ON reminder.contact_id = {$contactField} AND
1193 reminder.entity_id = e.id AND
1194 reminder.entity_table = '{$mapping->entity}' AND
1195 reminder.action_schedule_id = %1";
1198 // only consider reminders less than 11 months ago
1199 $reminderJoinClause .= " AND reminder.action_date_time > DATE_SUB({$now}, INTERVAL 11 MONTH)";
1202 if ($table != 'civicrm_contact e') {
1203 $join[] = "INNER JOIN civicrm_contact c ON c.id = {$contactField} AND c.is_deleted = 0 AND c.is_deceased = 0 ";
1206 if ($actionSchedule->start_action_date
) {
1207 $startDateClause = array();
1208 $op = ($actionSchedule->start_action_condition
== 'before' ?
'<=' : '>=');
1209 $operator = ($actionSchedule->start_action_condition
== 'before' ?
'DATE_SUB' : 'DATE_ADD');
1210 $date = $operator . "({$dateField}, INTERVAL {$actionSchedule->start_action_offset} {$actionSchedule->start_action_unit})";
1211 $startDateClause[] = "'{$now}' >= {$date}";
1212 if ($mapping->entity
== 'civicrm_participant') {
1213 $startDateClause[] = $operator . "({$now}, INTERVAL 1 DAY ) {$op} " . $dateField;
1216 $startDateClause[] = "DATE_SUB({$now}, INTERVAL 1 DAY ) <= {$date}";
1219 $startDate = implode(' AND ', $startDateClause);
1221 elseif ($actionSchedule->absolute_date
) {
1222 $startDate = "DATEDIFF(DATE('{$now}'),'{$actionSchedule->absolute_date}') = 0";
1225 // ( now >= date_built_from_start_time ) OR ( now = absolute_date )
1226 $dateClause = "reminder.id IS NULL AND {$startDate}";
1228 // start composing query
1229 $selectClause = 'SELECT ' . implode(', ', $select);
1230 $fromClause = "FROM $from";
1231 $joinClause = !empty($join) ?
implode(' ', $join) : '';
1232 $whereClause = 'WHERE ' . implode(' AND ', $where);
1233 $limitWhereClause = '';
1234 if (!empty($limitWhere)) {
1235 $limitWhereClause = ' AND ' . implode(' AND ', $limitWhere);
1239 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1243 LEFT JOIN {$reminderJoinClause}
1244 {$whereClause} {$limitWhereClause} AND {$dateClause} {$notINClause}
1246 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
1247 $isSendToAdditionalContacts = (!is_null($limitTo) && $limitTo == 0 && (!empty($addGroup) ||
!empty($addWhere))) ?
TRUE : FALSE;
1248 if ($isSendToAdditionalContacts) {
1249 $contactTable = "civicrm_contact c";
1250 $addSelect = "SELECT c.id as contact_id, c.id as entity_id, 'civicrm_contact' as entity_table, {$actionSchedule->id} as action_schedule_id";
1251 $additionReminderClause = "civicrm_action_log reminder ON reminder.contact_id = c.id AND
1252 reminder.entity_id = c.id AND
1253 reminder.entity_table = 'civicrm_contact' AND
1254 reminder.action_schedule_id = {$actionSchedule->id}";
1255 $addWhereClause = '';
1257 $addWhereClause = "AND {$addWhere}";
1259 $insertAdditionalSql = "
1260 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1262 FROM ({$contactTable})
1263 LEFT JOIN {$additionReminderClause}
1265 WHERE c.is_deleted = 0 AND c.is_deceased = 0
1269 SELECT rem.contact_id
1270 FROM civicrm_action_log rem INNER JOIN {$mapping->entity} e ON rem.entity_id = e.id
1271 WHERE rem.action_schedule_id = {$actionSchedule->id}
1272 AND rem.entity_table = '{$mapping->entity}'
1276 CRM_Core_DAO
::executeQuery($insertAdditionalSql);
1278 // if repeat is turned ON:
1279 if ($actionSchedule->is_repeat
) {
1280 $repeatEvent = ($actionSchedule->end_action
== 'before' ?
'DATE_SUB' : 'DATE_ADD') . "({$dateField}, INTERVAL {$actionSchedule->end_frequency_interval} {$actionSchedule->end_frequency_unit})";
1282 if ($actionSchedule->repetition_frequency_unit
== 'day') {
1283 $hrs = 24 * $actionSchedule->repetition_frequency_interval
;
1285 elseif ($actionSchedule->repetition_frequency_unit
== 'week') {
1286 $hrs = 24 * $actionSchedule->repetition_frequency_interval
* 7;
1288 elseif ($actionSchedule->repetition_frequency_unit
== 'month') {
1289 $hrs = "24*(DATEDIFF(DATE_ADD(latest_log_time, INTERVAL 1 MONTH ), latest_log_time))";
1291 elseif ($actionSchedule->repetition_frequency_unit
== 'year') {
1292 $hrs = "24*(DATEDIFF(DATE_ADD(latest_log_time, INTERVAL 1 YEAR ), latest_log_time))";
1295 $hrs = $actionSchedule->repetition_frequency_interval
;
1298 // (now <= repeat_end_time )
1299 $repeatEventClause = "'{$now}' <= {$repeatEvent}";
1300 // diff(now && logged_date_time) >= repeat_interval
1301 $havingClause = "HAVING TIMEDIFF({$now}, latest_log_time) >= TIME('{$hrs}:00:00')";
1302 $groupByClause = 'GROUP BY reminder.contact_id, reminder.entity_id, reminder.entity_table';
1303 $selectClause .= ', MAX(reminder.action_date_time) as latest_log_time';
1304 //CRM-15376 - do not send our reminders if original criteria no longer applies
1305 // the first part of the startDateClause array is the earliest the reminder can be sent. If the
1306 // event (e.g membership_end_date) has changed then the reminder may no longer apply
1307 // @todo - this only handles events that get moved later. Potentially they might get moved earlier
1308 $originalEventStartDateClause = empty($startDateClause) ?
'' : 'AND' . $startDateClause[0];
1309 $sqlInsertValues = "{$selectClause}
1312 INNER JOIN {$reminderJoinClause}
1313 {$whereClause} {$limitWhereClause} AND {$repeatEventClause} {$originalEventStartDateClause} {$notINClause}
1317 $valsqlInsertValues = CRM_Core_DAO
::executeQuery($sqlInsertValues, array(1 => array($actionSchedule->id
, 'Integer')));
1319 $arrValues = array();
1320 while ($valsqlInsertValues->fetch()) {
1321 $arrValues[] = "( {$valsqlInsertValues->contact_id}, {$valsqlInsertValues->entity_id}, '{$valsqlInsertValues->entity_table}',{$valsqlInsertValues->action_schedule_id} )";
1324 $valString = implode(',', $arrValues);
1328 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1329 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
1332 if ($isSendToAdditionalContacts) {
1333 $addSelect .= ', MAX(reminder.action_date_time) as latest_log_time';
1334 $sqlEndEventCheck = "
1335 SELECT * FROM {$table}
1336 {$whereClause} AND {$repeatEventClause} LIMIT 1";
1338 $daoCheck = CRM_Core_DAO
::executeQuery($sqlEndEventCheck);
1339 if ($daoCheck->fetch()) {
1340 $valSqlAdditionInsert = "
1342 FROM {$contactTable}
1344 INNER JOIN {$additionReminderClause}
1345 WHERE {$addWhere} AND c.is_deleted = 0 AND c.is_deceased = 0
1346 GROUP BY reminder.contact_id
1349 $daoForVals = CRM_Core_DAO
::executeQuery($valSqlAdditionInsert);
1350 $addValues = array();
1351 while ($daoForVals->fetch()) {
1352 $addValues[] = "( {$daoForVals->contact_id}, {$daoForVals->entity_id}, '{$daoForVals->entity_table}',{$daoForVals->action_schedule_id} )";
1354 $valString = implode(',', $addValues);
1358 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1359 CRM_Core_DAO
::executeQuery($query);
1370 * @return null|string
1372 public static function permissionedRelationships($field) {
1374 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
1375 FROM civicrm_membership m
1376 LEFT JOIN civicrm_membership cm ON cm.id = m.owner_membership_id
1377 LEFT JOIN civicrm_membership_type cmt ON cmt.id = m.membership_type_id
1378 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 )
1379 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 ) )
1380 WHERE m.owner_membership_id IS NOT NULL AND
1381 ( rel.is_permission_a_b = 0 OR rel.is_permission_b_a = 0)
1384 $excludeIds = array();
1385 $dao = CRM_Core_DAO
::executeQuery($query, array());
1386 while ($dao->fetch()) {
1387 if ($dao->slave_contact
== $dao->contact_id_a
&& $dao->is_permission_a_b
== 0) {
1388 $excludeIds[] = $dao->slave_contact
;
1390 elseif ($dao->slave_contact
== $dao->contact_id_b
&& $dao->is_permission_b_a
== 0) {
1391 $excludeIds[] = $dao->slave_contact
;
1395 if (!empty($excludeIds)) {
1396 $clause = "AND {$field} NOT IN ( " . implode(', ', $excludeIds) . ' ) ';
1404 * @param array $params
1408 public static function processQueue($now = NULL, $params = array()) {
1409 $now = $now ? CRM_Utils_Time
::setTime($now) : CRM_Utils_Time
::getTime();
1411 $mappings = self
::getMapping();
1412 foreach ($mappings as $mappingID => $mapping) {
1413 self
::buildRecipientContacts($mappingID, $now, $params);
1414 self
::sendMailings($mappingID, $now);
1419 'messages' => ts('Sent all scheduled reminders successfully'),
1426 * @param int $mappingID
1428 * @return null|string
1430 public static function isConfigured($id, $mappingID) {
1431 $queryString = "SELECT count(id) FROM civicrm_action_schedule
1432 WHERE mapping_id = %1 AND
1436 1 => array($mappingID, 'Integer'),
1437 2 => array($id, 'Integer'),
1439 return CRM_Core_DAO
::singleValueQuery($queryString, $params);
1443 * @param int $mappingID
1444 * @param $recipientType
1448 public static function getRecipientListing($mappingID, $recipientType) {
1450 if (!$mappingID ||
!$recipientType) {
1454 $mapping = self
::getMapping($mappingID);
1456 switch ($mapping['entity']) {
1457 case 'civicrm_participant':
1458 $eventContacts = CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
1459 if (empty($eventContacts[$recipientType])) {
1462 if ($eventContacts[$recipientType] == 'participant_role') {
1463 $options = CRM_Event_PseudoConstant
::participantRole();