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.
74 public static function getDateFields() {
75 $allFields = CRM_Core_BAO_CustomField
::getFields('');
77 'birth_date' => ts('Birth Date'),
78 'created_date' => ts('Created Date'),
79 'modified_date' => ts('Modified Date'),
81 foreach ($allFields as $fieldID => $field) {
82 if ($field['data_type'] == 'Date') {
83 $dateFields["custom_$fieldID"] = $field['label'];
90 * Retrieve list of selections/drop downs for Scheduled Reminder form
96 * associated array of all the drop downs in the form
98 public static function getSelection($id = NULL) {
99 $mapping = self
::getMapping();
100 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
101 $activityType = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE);
103 $participantStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label');
104 $event = CRM_Event_PseudoConstant
::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
105 $eventType = CRM_Event_PseudoConstant
::eventType();
106 $eventTemplate = CRM_Event_PseudoConstant
::eventTemplates();
107 $autoRenew = CRM_Core_OptionGroup
::values('auto_renew_options');
108 $membershipType = CRM_Member_PseudoConstant
::membershipType();
109 $dateFieldParams = array('data_type' => 'Date');
110 $dateFields = self
::getDateFields();
111 $contactOptions = CRM_Core_OptionGroup
::values('contact_date_reminder_options');
113 asort($activityType);
115 $sel1 = $sel2 = $sel3 = $sel4 = $sel5 = array();
117 'manual' => ts('Choose Recipient(s)'),
118 'group' => ts('Select Group'),
121 $entityMapping = array();
122 $recipientMapping = array_combine(array_keys($options), array_keys($options));
128 foreach ($mapping as $value) {
129 $entityValue = CRM_Utils_Array
::value('entity_value', $value);
130 $entityStatus = CRM_Utils_Array
::value('entity_status', $value);
131 $entityRecipient = CRM_Utils_Array
::value('entity_recipient', $value);
132 $valueLabel = array('- ' . strtolower(CRM_Utils_Array
::value('entity_value_label', $value)) . ' -');
133 $key = CRM_Utils_Array
::value('id', $value);
134 $entityMapping[$key] = CRM_Utils_Array
::value('entity', $value);
137 switch ($entityValue) {
138 case 'activity_type':
139 if ($value['entity'] == 'civicrm_activity') {
140 $sel1Val = ts('Activity');
142 $sel2[$key] = $valueLabel +
$activityType;
146 if ($value['entity'] == 'civicrm_participant') {
147 $sel1Val = ts('Event Type');
149 $sel2[$key] = $valueLabel +
$eventType;
152 case 'event_template':
153 if ($value['entity'] == 'civicrm_participant') {
154 $sel1Val = ts('Event Template');
156 $sel2[$key] = $valueLabel +
$eventTemplate;
159 case 'civicrm_event':
160 if ($value['entity'] == 'civicrm_participant') {
161 $sel1Val = ts('Event Name');
163 $sel2[$key] = $valueLabel +
$event;
166 case 'civicrm_membership_type':
167 if ($value['entity'] == 'civicrm_membership') {
168 $sel1Val = ts('Membership');
170 $sel2[$key] = $valueLabel +
$membershipType;
173 case 'civicrm_contact':
174 if ($value['entity'] == 'civicrm_contact') {
175 $sel1Val = ts('Contact');
177 $sel2[$key] = $dateFields;
180 $sel1[$key] = $sel1Val;
183 if ($startDate = CRM_Utils_Array
::value('entity_date_start', $value)) {
184 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
186 if ($endDate = CRM_Utils_Array
::value('entity_date_end', $value)) {
187 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
190 switch ($entityRecipient) {
191 case 'activity_contacts':
192 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts');
193 $sel5[$entityRecipient] = $activityContacts +
$options;
194 $recipientMapping +
= CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
197 case 'event_contacts':
198 $eventContacts = CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name');
199 $sel5[$entityRecipient] = $eventContacts +
$options;
200 $recipientMapping +
= CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
204 $sel5[$entityRecipient] = $options;
211 foreach ($mapping as $value) {
212 $entityStatus = CRM_Utils_Array
::value('entity_status', $value);
213 $statusLabel = array('- ' . strtolower(CRM_Utils_Array
::value('entity_status_label', $value)) . ' -');
214 $id = CRM_Utils_Array
::value('id', $value);
216 switch ($entityStatus) {
217 case 'activity_status':
218 foreach ($sel3[$id] as $kkey => & $vval) {
219 $vval = $statusLabel +
$activityStatus;
223 case 'civicrm_participant_status_type':
224 foreach ($sel3[$id] as $kkey => & $vval) {
225 $vval = $statusLabel +
$participantStatus;
229 case 'auto_renew_options':
230 foreach ($sel3[$id] as $kkey => & $vval) {
233 $auto = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $kkey, 'auto_renew');
236 $vval = $statusLabel +
$autoRenew;
239 $vval = $statusLabel;
244 case 'contact_date_reminder_options':
245 foreach ($sel3[$id] as $kkey => & $vval) {
246 $vval = $contactOptions;
262 'entityMapping' => $entityMapping,
263 'recipientMapping' => $recipientMapping,
269 * @param int $isLimit
273 public static function getSelection1($id = NULL, $isLimit = NULL) {
274 $mapping = self
::getMapping($id);
275 $sel4 = $sel5 = array();
277 'manual' => ts('Choose Recipient(s)'),
278 'group' => ts('Select Group'),
281 $recipientMapping = array_combine(array_keys($options), array_keys($options));
283 foreach ($mapping as $value) {
284 $entityRecipient = CRM_Utils_Array
::value('entity_recipient', $value);
285 $key = CRM_Utils_Array
::value('id', $value);
287 if ($startDate = CRM_Utils_Array
::value('entity_date_start', $value)) {
288 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
290 if ($endDate = CRM_Utils_Array
::value('entity_date_end', $value)) {
291 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
294 switch ($entityRecipient) {
295 case 'activity_contacts':
296 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts');
297 $sel5[$id] = $activityContacts +
$options;
298 $recipientMapping +
= CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
301 case 'event_contacts':
302 //CRM-15536, don't provide participant_role option on choosing 'Also Include' for Event entity
304 $options +
= CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name');
306 $sel5[$id] = $options;
307 $recipientMapping +
= CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
311 $sel5[$id] = $options;
318 'sel5' => $sel5[$id],
319 'recipientMapping' => $recipientMapping,
324 * Retrieve list of Scheduled Reminders.
326 * @param bool $namesOnly
327 * Return simple list of names.
329 * @param null $entityValue
333 * (reference) reminder list
335 public static function &getList($namesOnly = FALSE, $entityValue = NULL, $id = NULL) {
336 $activity_type = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE);
337 $activity_status = CRM_Core_PseudoConstant
::activityStatus();
339 $event_type = CRM_Event_PseudoConstant
::eventType();
340 $civicrm_event = CRM_Event_PseudoConstant
::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
341 $civicrm_participant_status_type = CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label');
342 $event_template = CRM_Event_PseudoConstant
::eventTemplates();
343 $civicrm_contact = self
::getDateFields();
345 $auto_renew_options = CRM_Core_OptionGroup
::values('auto_renew_options');
346 $contact_date_reminder_options = CRM_Core_OptionGroup
::values('contact_date_reminder_options');
347 $civicrm_membership_type = CRM_Member_PseudoConstant
::membershipType();
350 'civicrm_activity' => 'Activity',
351 'civicrm_participant' => 'Event',
352 'civicrm_membership' => 'Member',
353 'civicrm_contact' => 'Contact',
361 cam.entity_value as entityValue,
362 cas.entity_value as entityValueIds,
363 cam.entity_status as entityStatus,
364 cas.entity_status as entityStatusIds,
365 cas.start_action_date as entityDate,
366 cas.start_action_offset,
367 cas.start_action_unit,
368 cas.start_action_condition,
373 FROM civicrm_action_schedule cas
374 LEFT JOIN civicrm_action_mapping cam ON (cam.id = cas.mapping_id)
376 $params = CRM_Core_DAO
::$_nullArray;
377 $where = " WHERE 1 ";
378 if ($entityValue and $id) {
380 AND cas.entity_value = $id AND
381 cam.entity_value = '$entityValue'";
384 1 => array($id, 'Integer'),
385 2 => array($entityValue, 'String'),
388 $where .= " AND cas.used_for IS NULL";
390 $dao = CRM_Core_DAO
::executeQuery($query);
391 while ($dao->fetch()) {
392 $list[$dao->id
]['id'] = $dao->id
;
393 $list[$dao->id
]['title'] = $dao->title
;
394 $list[$dao->id
]['start_action_offset'] = $dao->start_action_offset
;
395 $list[$dao->id
]['start_action_unit'] = $dao->start_action_unit
;
396 $list[$dao->id
]['start_action_condition'] = $dao->start_action_condition
;
397 $list[$dao->id
]['entityDate'] = ucwords(str_replace('_', ' ', $dao->entityDate
));
398 $list[$dao->id
]['absolute_date'] = $dao->absolute_date
;
400 $status = $dao->entityStatus
;
401 $statusArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityStatusIds
);
402 foreach ($statusArray as & $s) {
403 $s = CRM_Utils_Array
::value($s, $
$status);
405 $statusIds = implode(', ', $statusArray);
407 $value = $dao->entityValue
;
408 $valueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityValueIds
);
409 foreach ($valueArray as & $v) {
410 $v = CRM_Utils_Array
::value($v, $
$value);
412 $valueIds = implode(', ', $valueArray);
413 $list[$dao->id
]['entity'] = $entity[$dao->entity
];
414 $list[$dao->id
]['value'] = $valueIds;
415 $list[$dao->id
]['status'] = $statusIds;
416 $list[$dao->id
]['is_repeat'] = $dao->is_repeat
;
417 $list[$dao->id
]['is_active'] = $dao->is_active
;
424 * @param int $contactId
426 * @param int $scheduleID
428 * @param array $tokenParams
431 * @throws CRM_Core_Exception
433 public static function sendReminder($contactId, $to, $scheduleID, $from, $tokenParams) {
434 $email = $to['email'];
435 $phoneNumber = $to['phone'];
436 $schedule = new CRM_Core_DAO_ActionSchedule();
437 $schedule->id
= $scheduleID;
439 $domain = CRM_Core_BAO_Domain
::getDomain();
441 $hookTokens = array();
443 if ($schedule->find(TRUE)) {
444 $body_text = $schedule->body_text
;
445 $body_html = $schedule->body_html
;
446 $sms_body_text = $schedule->sms_body_text
;
447 $body_subject = $schedule->subject
;
449 $body_text = CRM_Utils_String
::htmlToText($body_html);
452 $params = array(array('contact_id', '=', $contactId, 0, 0));
453 list($contact, $_) = CRM_Contact_BAO_Query
::apiQuery($params);
456 $contact = reset($contact);
458 if (!$contact ||
is_a($contact, 'CRM_Core_Error')) {
462 // merge activity tokens with contact array
463 $contact = array_merge($contact, $tokenParams);
466 CRM_Utils_Hook
::tokenValues($contact, $contactId);
468 CRM_Utils_Hook
::tokens($hookTokens);
469 $categories = array_keys($hookTokens);
471 $type = array('body_html' => 'html', 'body_text' => 'text', 'sms_body_text' => 'text');
473 foreach ($type as $bodyType => $value) {
474 $dummy_mail = new CRM_Mailing_BAO_Mailing();
475 if ($bodyType == 'sms_body_text') {
476 $dummy_mail->body_text
= $
$bodyType;
479 $dummy_mail->$bodyType = $
$bodyType;
481 $tokens = $dummy_mail->getTokens();
484 CRM_Utils_Token
::replaceGreetingTokens($
$bodyType, NULL, $contact['contact_id']);
485 $
$bodyType = CRM_Utils_Token
::replaceDomainTokens($
$bodyType, $domain, TRUE, $tokens[$value], TRUE);
486 $
$bodyType = CRM_Utils_Token
::replaceContactTokens($
$bodyType, $contact, FALSE, $tokens[$value], FALSE, TRUE);
487 $
$bodyType = CRM_Utils_Token
::replaceComponentTokens($
$bodyType, $contact, $tokens[$value], TRUE, FALSE);
488 $
$bodyType = CRM_Utils_Token
::replaceHookTokens($
$bodyType, $contact, $categories, TRUE);
493 $sms_text = $sms_body_text;
495 $smarty = CRM_Core_Smarty
::singleton();
501 $
$elem = $smarty->fetch("string:{$$elem}");
504 //@todo - this next section is a duplicate of function CRM_Utils_Token::getTokens
506 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
512 $subjectToken = NULL;
514 foreach ($matches[1] as $token) {
515 list($type, $name) = preg_split('/\./', $token, 2);
517 if (!isset($subjectToken[$type])) {
518 $subjectToken[$type] = array();
520 $subjectToken[$type][] = $name;
525 // @todo this (along with the copy-&-paste chunk above is a commonly repeated chunk of code & should be in a re-usable function
526 $messageSubject = CRM_Utils_Token
::replaceContactTokens($body_subject, $contact, FALSE, $subjectToken);
527 $messageSubject = CRM_Utils_Token
::replaceDomainTokens($messageSubject, $domain, TRUE, $subjectToken);
528 $messageSubject = CRM_Utils_Token
::replaceComponentTokens($messageSubject, $contact, $subjectToken, TRUE);
529 $messageSubject = CRM_Utils_Token
::replaceHookTokens($messageSubject, $contact, $categories, TRUE);
531 $messageSubject = $smarty->fetch("string:{$messageSubject}");
533 if ($schedule->mode
== 'SMS' or $schedule->mode
== 'User_Preference') {
534 $session = CRM_Core_Session
::singleton();
535 $userID = $session->get('userID') ?
$session->get('userID') : $contactId;
537 'To' => $phoneNumber,
538 'provider_id' => $schedule->sms_provider_id
,
539 'activity_subject' => $messageSubject,
541 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
545 $activityParams = array(
546 'source_contact_id' => $userID,
547 'activity_type_id' => $activityTypeID,
548 'activity_date_time' => date('YmdHis'),
549 'subject' => $messageSubject,
550 'details' => $sms_text,
551 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
554 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
556 CRM_Activity_BAO_Activity
::sendSMSMessage($contactId,
564 if ($schedule->mode
== 'Email' or $schedule->mode
== 'User_Preference') {
565 // set up the parameters for CRM_Utils_Mail::send
567 'groupName' => 'Scheduled Reminder Sender',
569 'toName' => $contact['display_name'],
571 'subject' => $messageSubject,
572 'entity' => 'action_schedule',
573 'entity_id' => $scheduleID,
576 if (!$html ||
$contact['preferred_mail_format'] == 'Text' ||
577 $contact['preferred_mail_format'] == 'Both'
579 // render the & entities in text mode, so that the links work
580 $mailParams['text'] = str_replace('&', '&', $text);
582 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
583 $contact['preferred_mail_format'] == 'Both'
586 $mailParams['html'] = $html;
588 $result = CRM_Utils_Mail
::send($mailParams);
597 * Add the schedules reminders in the db.
599 * @param array $params
600 * (reference ) an assoc array of name/value pairs.
604 * @return CRM_Core_DAO_ActionSchedule
606 public static function add(&$params, $ids = array()) {
607 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
608 $actionSchedule->copyValues($params);
610 return $actionSchedule->save();
614 * Retrieve DB object based on input parameters.
616 * It also stores all the retrieved values in the default array.
618 * @param array $params
619 * (reference ) an assoc array of name/value pairs.
620 * @param array $values
621 * (reference ) an assoc array to hold the flattened values.
623 * @return CRM_Core_DAO_ActionSchedule|null
624 * object on success, null otherwise
626 public static function retrieve(&$params, &$values) {
627 if (empty($params)) {
630 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
632 $actionSchedule->copyValues($params);
634 if ($actionSchedule->find(TRUE)) {
635 $ids['actionSchedule'] = $actionSchedule->id
;
637 CRM_Core_DAO
::storeValues($actionSchedule, $values);
639 return $actionSchedule;
648 * ID of the Reminder to be deleted.
651 public static function del($id) {
653 $dao = new CRM_Core_DAO_ActionSchedule();
655 if ($dao->find(TRUE)) {
660 CRM_Core_Error
::fatal(ts('Invalid value passed to delete function.'));
664 * Update the is_active flag in the db.
667 * Id of the database record.
668 * @param bool $is_active
669 * Value we want to set the is_active field.
672 * DAO object on success, null otherwise
674 public static function setIsActive($id, $is_active) {
675 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
679 * @param int $mappingID
682 * @throws CRM_Core_Exception
684 public static function sendMailings($mappingID, $now) {
685 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
686 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
688 $mapping = new CRM_Core_DAO_ActionMapping();
689 $mapping->id
= $mappingID;
690 $mapping->find(TRUE);
692 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
693 $actionSchedule->mapping_id
= $mappingID;
694 $actionSchedule->is_active
= 1;
695 $actionSchedule->find(FALSE);
697 $tokenFields = array();
698 $session = CRM_Core_Session
::singleton();
700 while ($actionSchedule->fetch()) {
701 $extraSelect = $extraJoin = $extraWhere = $extraOn = '';
703 if ($actionSchedule->from_email
) {
704 $fromEmailAddress = "$actionSchedule->from_name <$actionSchedule->from_email>";
707 $activityTypeID = FALSE;
708 $activityStatusID = FALSE;
709 if ($actionSchedule->record_activity
) {
710 if ($mapping->entity
== 'civicrm_membership') {
712 = CRM_Core_OptionGroup
::getValue('activity_type', 'Membership Renewal Reminder', 'name');
716 = CRM_Core_OptionGroup
::getValue('activity_type', 'Reminder Sent', 'name');
720 = CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
723 if ($mapping->entity
== 'civicrm_activity') {
724 $compInfo = CRM_Core_Component
::getEnabledComponents();
725 $tokenEntity = 'activity';
726 $tokenFields = array('activity_id', 'activity_type', 'subject', 'details', 'activity_date_time');
727 $extraSelect = ', ov.label as activity_type, e.id as activity_id';
729 INNER JOIN civicrm_option_group og ON og.name = 'activity_type'
730 INNER JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
731 $extraOn = ' AND e.is_current_revision = 1 AND e.is_deleted = 0 ';
732 if ($actionSchedule->limit_to
== 0) {
734 LEFT JOIN civicrm_option_group og ON og.name = 'activity_type'
735 LEFT JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
739 // if CiviCase component is enabled
740 if (array_key_exists('CiviCase', $compInfo)) {
741 $extraSelect .= ", civicrm_case_activity.case_id as case_id";
743 LEFT JOIN `civicrm_case_activity` ON `e`.`id` = `civicrm_case_activity`.`activity_id`";
747 if ($mapping->entity
== 'civicrm_participant') {
748 $tokenEntity = 'event';
749 $tokenFields = array(
765 $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 ';
768 INNER JOIN civicrm_event ev ON e.event_id = ev.id
769 INNER JOIN civicrm_option_group og ON og.name = 'event_type'
770 INNER JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
771 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
772 LEFT JOIN civicrm_address address ON address.id = lb.address_id
773 LEFT JOIN civicrm_email email ON email.id = lb.email_id
774 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
776 if ($actionSchedule->limit_to
== 0) {
778 LEFT JOIN civicrm_event ev ON e.event_id = ev.id
779 LEFT JOIN civicrm_option_group og ON og.name = 'event_type'
780 LEFT JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
781 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
782 LEFT JOIN civicrm_address address ON address.id = lb.address_id
783 LEFT JOIN civicrm_email email ON email.id = lb.email_id
784 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
789 if ($mapping->entity
== 'civicrm_membership') {
790 $tokenEntity = 'membership';
791 $tokenFields = array('fee', 'id', 'join_date', 'start_date', 'end_date', 'status', 'type');
792 $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';
794 INNER JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
795 INNER JOIN civicrm_membership_status ms ON e.status_id = ms.id';
797 if ($actionSchedule->limit_to
== 0) {
799 LEFT JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
800 LEFT JOIN civicrm_membership_status ms ON e.status_id = ms.id';
804 if ($mapping->entity
== 'civicrm_contact') {
805 $tokenEntity = 'contact';
806 //TODO: get full list somewhere!
807 $tokenFields = array('birth_date', 'last_name');
808 //TODO: is there anything to add here?
811 $entityJoinClause = "INNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
812 if ($actionSchedule->limit_to
== 0) {
813 $entityJoinClause = "LEFT JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
814 $extraWhere .= " AND (e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact')";
816 $entityJoinClause .= $extraOn;
819 SELECT reminder.id as reminderID, reminder.contact_id as contactID, reminder.entity_table as entityTable, reminder.*, e.id as entityID, e.* {$extraSelect}
820 FROM civicrm_action_log reminder
823 WHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL
826 $dao = CRM_Core_DAO
::executeQuery($query,
827 array(1 => array($actionSchedule->id
, 'Integer'))
830 while ($dao->fetch()) {
831 $entityTokenParams = array();
832 foreach ($tokenFields as $field) {
833 if ($field == 'location') {
835 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
836 $loc['street_address'] = $dao->street_address
;
837 $loc['city'] = $dao->city
;
838 $loc['state_province'] = CRM_Utils_Array
::value($dao->state_province_id
, $stateProvince);
839 $loc['postal_code'] = $dao->postal_code
;
840 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address
::format($loc);
842 elseif ($field == 'info_url') {
843 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
845 elseif ($field == 'registration_url') {
846 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
848 elseif (in_array($field, array('start_date', 'end_date', 'join_date', 'activity_date_time'))) {
849 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date
::customFormat($dao->$field);
851 elseif ($field == 'balance') {
852 if ($dao->entityTable
== 'civicrm_contact') {
855 elseif (!empty($dao->entityID
)) {
856 $info = CRM_Contribute_BAO_Contribution
::getPaymentInfo($dao->entityID
, 'event');
857 $balancePay = CRM_Utils_Array
::value('balance', $info);
858 $balancePay = CRM_Utils_Money
::format($balancePay);
860 $entityTokenParams["{$tokenEntity}." . $field] = $balancePay;
862 elseif ($field == 'fee_amount') {
863 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Money
::format($dao->$field);
866 $entityTokenParams["{$tokenEntity}." . $field] = $dao->$field;
871 $errorMsg = $toEmail = $toPhoneNumber = '';
873 if ($actionSchedule->mode
== 'SMS' or $actionSchedule->mode
== 'User_Preference') {
874 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
875 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($dao->contactID
, FALSE, 'Mobile', $filters);
876 //to get primary mobile ph,if not get a first mobile phONE
877 if (!empty($toPhoneNumbers)) {
878 $toPhoneNumberDetails = reset($toPhoneNumbers);
879 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumberDetails);
880 //contact allows to send sms
884 if ($actionSchedule->mode
== 'Email' or $actionSchedule->mode
== 'User_Preference') {
885 $toEmail = CRM_Contact_BAO_Contact
::getPrimaryEmail($dao->contactID
);
887 if ($toEmail ||
!(empty($toPhoneNumber) or $toDoNotSms)) {
888 $to['email'] = $toEmail;
889 $to['phone'] = $toPhoneNumber;
891 = CRM_Core_BAO_ActionSchedule
::sendReminder(
899 if (!$result ||
is_a($result, 'PEAR_Error')) {
900 // we could not send an email, for now we ignore, CRM-3406
906 $errorMsg = "Couldn\'t find recipient\'s email address.";
909 // update action log record
911 'id' => $dao->reminderID
,
912 'is_error' => $isError,
913 'message' => $errorMsg ?
$errorMsg : "null",
914 'action_date_time' => $now,
916 CRM_Core_BAO_ActionLog
::create($logParams);
918 // insert activity log record if needed
919 if ($actionSchedule->record_activity
&& !$isError) {
920 $activityParams = array(
921 'subject' => $actionSchedule->title
,
922 'details' => $actionSchedule->body_html
,
923 'source_contact_id' => $session->get('userID') ?
$session->get('userID') : $dao->contactID
,
924 'target_contact_id' => $dao->contactID
,
925 'activity_date_time' => date('YmdHis'),
926 'status_id' => $activityStatusID,
927 'activity_type_id' => $activityTypeID,
928 'source_record_id' => $dao->entityID
,
930 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
932 //file reminder on case if source activity is a case activity
933 if (!empty($dao->case_id
)) {
934 $caseActivityParams = array();
935 $caseActivityParams['case_id'] = $dao->case_id
;
936 $caseActivityParams['activity_id'] = $activity->id
;
937 CRM_Case_BAO_Case
::processCaseActivity($caseActivityParams);
947 * @param int $mappingID
949 * @param array $params
951 * @throws API_Exception
953 public static function buildRecipientContacts($mappingID, $now, $params = array()) {
954 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
955 $actionSchedule->mapping_id
= $mappingID;
956 $actionSchedule->is_active
= 1;
957 if (!empty($params)) {
958 _civicrm_api3_dao_set_filter($actionSchedule, $params, FALSE);
960 $actionSchedule->find();
962 while ($actionSchedule->fetch()) {
963 $mapping = new CRM_Core_DAO_ActionMapping();
964 $mapping->id
= $mappingID;
965 $mapping->find(TRUE);
967 // note: $where - this filtering applies for both
968 // 'limit to' and 'addition to' options
969 // $limitWhere - this filtering applies only for
971 $select = $join = $where = $limitWhere = array();
972 $selectColumns = "contact_id, entity_id, entity_table, action_schedule_id";
973 $limitTo = $actionSchedule->limit_to
;
974 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
975 trim($actionSchedule->entity_value
, CRM_Core_DAO
::VALUE_SEPARATOR
)
977 $value = implode(',', $value);
979 $status = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
980 trim($actionSchedule->entity_status
, CRM_Core_DAO
::VALUE_SEPARATOR
)
982 $status = implode(',', $status);
984 $anniversary = FALSE;
986 if (!CRM_Utils_System
::isNull($mapping->entity_recipient
)) {
987 if ($mapping->entity_recipient
== 'event_contacts') {
988 $recipientOptions = CRM_Core_OptionGroup
::values($mapping->entity_recipient
, FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
991 $recipientOptions = CRM_Core_OptionGroup
::values($mapping->entity_recipient
, FALSE, FALSE, FALSE, NULL, 'name');
994 $from = "{$mapping->entity} e";
996 if ($mapping->entity
== 'civicrm_activity') {
997 $contactField = 'r.contact_id';
998 $table = 'civicrm_activity e';
999 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1000 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1001 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
1002 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
1004 if (!is_null($limitTo)) {
1005 if ($limitTo == 0) {
1006 // including the activity target contacts if 'in addition' is defined
1007 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
1010 switch (CRM_Utils_Array
::value($actionSchedule->recipient
, $recipientOptions)) {
1011 case 'Activity Assignees':
1012 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$assigneeID}";
1015 case 'Activity Source':
1016 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$sourceID}";
1020 case 'Activity Targets':
1021 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
1026 // build where clause
1027 if (!empty($value)) {
1028 $where[] = "e.activity_type_id IN ({$value})";
1031 $where[] = "e.activity_type_id IS NULL";
1033 if (!empty($status)) {
1034 $where[] = "e.status_id IN ({$status})";
1036 $where[] = ' e.is_current_revision = 1 ';
1037 $where[] = ' e.is_deleted = 0 ';
1039 $dateField = 'e.activity_date_time';
1042 if ($mapping->entity
== 'civicrm_participant') {
1043 $table = 'civicrm_event r';
1044 $contactField = 'e.contact_id';
1045 $join[] = 'INNER JOIN civicrm_event r ON e.event_id = r.id';
1046 if ($actionSchedule->recipient_listing
&& $limitTo) {
1047 $rList = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1048 trim($actionSchedule->recipient_listing
, CRM_Core_DAO
::VALUE_SEPARATOR
)
1050 $rList = implode(',', $rList);
1052 switch ($recipientOptions[$actionSchedule->recipient
]) {
1053 case 'participant_role':
1054 $where[] = "e.role_id IN ({$rList})";
1062 // build where clause
1063 if (!empty($value)) {
1064 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IN ({$value})" : "r.id IN ({$value})";
1067 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IS NULL" : "r.id IS NULL";
1070 // participant status criteria not to be implemented
1071 // for additional recipients
1072 if (!empty($status)) {
1073 $limitWhere[] = "e.status_id IN ({$status})";
1076 $where[] = 'r.is_active = 1';
1077 $where[] = 'r.is_template = 0';
1078 $dateField = str_replace('event_', 'r.', $actionSchedule->start_action_date
);
1082 if ($mapping->entity
== 'civicrm_membership') {
1083 $contactField = 'e.contact_id';
1084 $table = 'civicrm_membership e';
1085 // build where clause
1087 //auto-renew memberships
1088 $where[] = "e.contribution_recur_id IS NOT NULL ";
1090 elseif ($status == 1) {
1091 $where[] = "e.contribution_recur_id IS NULL ";
1094 // build where clause
1095 if (!empty($value)) {
1096 $where[] = "e.membership_type_id IN ({$value})";
1099 $where[] = "e.membership_type_id IS NULL";
1102 $where[] = "( e.is_override IS NULL OR e.is_override = 0 )";
1103 $dateField = str_replace('membership_', 'e.', $actionSchedule->start_action_date
);
1104 $notINClause = self
::permissionedRelationships($contactField);
1106 $membershipStatus = CRM_Member_PseudoConstant
::membershipStatus(NULL, "(is_current_member = 1 OR name = 'Expired')", 'id');
1107 $mStatus = implode(',', $membershipStatus);
1108 $where[] = "e.status_id IN ({$mStatus})";
1110 // We are not tracking the reference date for 'repeated' schedule reminders,
1111 // for further details please check CRM-15376
1112 if ($actionSchedule->start_action_date
&& $actionSchedule->is_repeat
== FALSE) {
1113 $select[] = $dateField;
1114 $selectColumns = "reference_date, " . $selectColumns;
1118 if ($mapping->entity
== 'civicrm_contact') {
1119 $contactFields = array(
1124 if (in_array($value, $contactFields)) {
1125 $dateDBField = $value;
1126 $table = 'civicrm_contact e';
1127 $contactField = 'e.id';
1128 $where[] = 'e.is_deleted = 0';
1129 $where[] = 'e.is_deceased = 0';
1133 $customFieldParams = array('id' => substr($value, 7));
1134 $customGroup = $customField = array();
1135 CRM_Core_BAO_CustomField
::retrieve($customFieldParams, $customField);
1136 $dateDBField = $customField['column_name'];
1137 $customGroupParams = array('id' => $customField['custom_group_id'], $customGroup);
1138 CRM_Core_BAO_CustomGroup
::retrieve($customGroupParams, $customGroup);
1139 $from = $table = "{$customGroup['table_name']} e";
1140 $contactField = 'e.entity_id';
1141 $where[] = '1'; // possible to have no "where" in this case
1144 $status_ = explode(',', $status);
1145 if (in_array(2, $status_)) {
1146 // anniversary mode:
1147 $dateField = 'DATE_ADD(e.' . $dateDBField . ', INTERVAL ROUND(DATEDIFF(DATE(' . $now . '), e.' . $dateDBField . ') / 365) YEAR)';
1148 $anniversary = TRUE;
1152 $dateField = 'e.' . $dateDBField;
1156 // CRM-13577 Introduce Smart Groups Handling
1157 if ($actionSchedule->group_id
) {
1159 // Need to check if its a smart group or not
1160 // Then decide which table to join onto the query
1161 $group = CRM_Contact_DAO_Group
::getTableName();
1163 // Get the group information
1165 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
1167 WHERE $group.id = {$actionSchedule->group_id}
1170 $groupDAO = CRM_Core_DAO
::executeQuery($sql);
1171 $isSmartGroup = FALSE;
1173 $groupDAO->fetch() &&
1174 !empty($groupDAO->saved_search_id
)
1176 // Check that the group is in place in the cache and up to date
1177 CRM_Contact_BAO_GroupContactCache
::check($actionSchedule->group_id
);
1178 // Set smart group flag
1179 $isSmartGroup = TRUE;
1182 // CRM-13577 End Introduce Smart Groups Handling
1185 if ($actionSchedule->group_id
) {
1186 // CRM-13577 If smart group then use Cache table
1187 if ($isSmartGroup) {
1188 $join[] = "INNER JOIN civicrm_group_contact_cache grp ON {$contactField} = grp.contact_id";
1189 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1192 $join[] = "INNER JOIN civicrm_group_contact grp ON {$contactField} = grp.contact_id AND grp.status = 'Added'";
1193 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1196 elseif (!empty($actionSchedule->recipient_manual
)) {
1197 $rList = CRM_Utils_Type
::escape($actionSchedule->recipient_manual
, 'String');
1198 $where[] = "{$contactField} IN ({$rList})";
1201 elseif (!is_null($limitTo)) {
1202 $addGroup = $addWhere = '';
1203 if ($actionSchedule->group_id
) {
1204 // CRM-13577 If smart group then use Cache table
1205 if ($isSmartGroup) {
1206 $addGroup = " INNER JOIN civicrm_group_contact_cache grp ON c.id = grp.contact_id";
1207 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1210 $addGroup = " INNER JOIN civicrm_group_contact grp ON c.id = grp.contact_id AND grp.status = 'Added'";
1211 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1214 if (!empty($actionSchedule->recipient_manual
)) {
1215 $rList = CRM_Utils_Type
::escape($actionSchedule->recipient_manual
, 'String');
1216 $addWhere = "c.id IN ({$rList})";
1220 $select[] = "{$contactField} as contact_id";
1221 $select[] = 'e.id as entity_id';
1222 $select[] = "'{$mapping->entity}' as entity_table";
1223 $select[] = "{$actionSchedule->id} as action_schedule_id";
1224 $reminderJoinClause = "civicrm_action_log reminder ON reminder.contact_id = {$contactField} AND
1225 reminder.entity_id = e.id AND
1226 reminder.entity_table = '{$mapping->entity}' AND
1227 reminder.action_schedule_id = %1";
1230 // only consider reminders less than 11 months ago
1231 $reminderJoinClause .= " AND reminder.action_date_time > DATE_SUB({$now}, INTERVAL 11 MONTH)";
1234 if ($table != 'civicrm_contact e') {
1235 $join[] = "INNER JOIN civicrm_contact c ON c.id = {$contactField} AND c.is_deleted = 0 AND c.is_deceased = 0 ";
1238 if ($actionSchedule->start_action_date
) {
1239 $startDateClause = array();
1240 $op = ($actionSchedule->start_action_condition
== 'before' ?
'<=' : '>=');
1241 $operator = ($actionSchedule->start_action_condition
== 'before' ?
'DATE_SUB' : 'DATE_ADD');
1242 $date = $operator . "({$dateField}, INTERVAL {$actionSchedule->start_action_offset} {$actionSchedule->start_action_unit})";
1243 $startDateClause[] = "'{$now}' >= {$date}";
1244 if ($mapping->entity
== 'civicrm_participant') {
1245 $startDateClause[] = $operator . "({$now}, INTERVAL 1 DAY ) {$op} " . $dateField;
1248 $startDateClause[] = "DATE_SUB({$now}, INTERVAL 1 DAY ) <= {$date}";
1251 $startDate = implode(' AND ', $startDateClause);
1253 elseif ($actionSchedule->absolute_date
) {
1254 $startDate = "DATEDIFF(DATE('{$now}'),'{$actionSchedule->absolute_date}') = 0";
1257 // ( now >= date_built_from_start_time ) OR ( now = absolute_date )
1258 $dateClause = "reminder.id IS NULL AND {$startDate}";
1260 // start composing query
1261 $selectClause = 'SELECT ' . implode(', ', $select);
1262 $fromClause = "FROM $from";
1263 $joinClause = !empty($join) ?
implode(' ', $join) : '';
1264 $whereClause = 'WHERE ' . implode(' AND ', $where);
1265 $limitWhereClause = '';
1266 if (!empty($limitWhere)) {
1267 $limitWhereClause = ' AND ' . implode(' AND ', $limitWhere);
1271 INSERT INTO civicrm_action_log ({$selectColumns})
1275 LEFT JOIN {$reminderJoinClause}
1276 {$whereClause} {$limitWhereClause} AND {$dateClause} {$notINClause}
1279 // In some cases reference_date got outdated due to many reason e.g. In Membership renewal end_date got extended
1280 // which means reference date mismatches with the end_date where end_date may be used as the start_action_date
1281 // criteria for some schedule reminder so in order to send new reminder we INSERT new reminder with new reference_date
1282 // value via UNION operation
1283 if (strpos($selectColumns, 'reference_date') !== FALSE) {
1284 $dateClause = str_replace('reminder.id IS NULL', 'reminder.id IS NOT NULL', $dateClause);
1286 INSERT INTO civicrm_action_log ({$selectColumns})
1290 LEFT JOIN {$reminderJoinClause}
1291 {$whereClause} {$limitWhereClause} {$notINClause} AND {$dateClause} AND
1292 reminder.action_date_time IS NOT NULL AND
1293 reminder.reference_date IS NOT NULL
1294 GROUP BY reminder.id, reminder.reference_date
1295 HAVING reminder.id = MAX(reminder.id) AND reminder.reference_date <> {$dateField}
1299 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
1301 if (!empty($referenceQuery)) {
1302 CRM_Core_DAO
::executeQuery($referenceQuery, array(1 => array($actionSchedule->id
, 'Integer')));
1305 $isSendToAdditionalContacts = (!is_null($limitTo) && $limitTo == 0 && (!empty($addGroup) ||
!empty($addWhere))) ?
TRUE : FALSE;
1306 if ($isSendToAdditionalContacts) {
1307 $contactTable = "civicrm_contact c";
1308 $addSelect = "SELECT c.id as contact_id, c.id as entity_id, 'civicrm_contact' as entity_table, {$actionSchedule->id} as action_schedule_id";
1309 $additionReminderClause = "civicrm_action_log reminder ON reminder.contact_id = c.id AND
1310 reminder.entity_id = c.id AND
1311 reminder.entity_table = 'civicrm_contact' AND
1312 reminder.action_schedule_id = {$actionSchedule->id}";
1313 $addWhereClause = '';
1315 $addWhereClause = "AND {$addWhere}";
1317 $insertAdditionalSql = "
1318 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1320 FROM ({$contactTable})
1321 LEFT JOIN {$additionReminderClause}
1323 WHERE c.is_deleted = 0 AND c.is_deceased = 0
1327 SELECT rem.contact_id
1328 FROM civicrm_action_log rem INNER JOIN {$mapping->entity} e ON rem.entity_id = e.id
1329 WHERE rem.action_schedule_id = {$actionSchedule->id}
1330 AND rem.entity_table = '{$mapping->entity}'
1334 CRM_Core_DAO
::executeQuery($insertAdditionalSql);
1336 // if repeat is turned ON:
1337 if ($actionSchedule->is_repeat
) {
1338 $repeatEvent = ($actionSchedule->end_action
== 'before' ?
'DATE_SUB' : 'DATE_ADD') . "({$dateField}, INTERVAL {$actionSchedule->end_frequency_interval} {$actionSchedule->end_frequency_unit})";
1340 if ($actionSchedule->repetition_frequency_unit
== 'day') {
1341 $hrs = 24 * $actionSchedule->repetition_frequency_interval
;
1343 elseif ($actionSchedule->repetition_frequency_unit
== 'week') {
1344 $hrs = 24 * $actionSchedule->repetition_frequency_interval
* 7;
1346 elseif ($actionSchedule->repetition_frequency_unit
== 'month') {
1347 $hrs = "24*(DATEDIFF(DATE_ADD(latest_log_time, INTERVAL 1 MONTH ), latest_log_time))";
1349 elseif ($actionSchedule->repetition_frequency_unit
== 'year') {
1350 $hrs = "24*(DATEDIFF(DATE_ADD(latest_log_time, INTERVAL 1 YEAR ), latest_log_time))";
1353 $hrs = $actionSchedule->repetition_frequency_interval
;
1356 // (now <= repeat_end_time )
1357 $repeatEventClause = "'{$now}' <= {$repeatEvent}";
1358 // diff(now && logged_date_time) >= repeat_interval
1359 $havingClause = "HAVING TIMEDIFF({$now}, latest_log_time) >= TIME('{$hrs}:00:00')";
1360 $groupByClause = 'GROUP BY reminder.contact_id, reminder.entity_id, reminder.entity_table';
1361 $selectClause .= ', MAX(reminder.action_date_time) as latest_log_time';
1362 //CRM-15376 - do not send our reminders if original criteria no longer applies
1363 // the first part of the startDateClause array is the earliest the reminder can be sent. If the
1364 // event (e.g membership_end_date) has changed then the reminder may no longer apply
1365 // @todo - this only handles events that get moved later. Potentially they might get moved earlier
1366 $originalEventStartDateClause = empty($startDateClause) ?
'' : 'AND' . $startDateClause[0];
1367 $sqlInsertValues = "{$selectClause}
1370 INNER JOIN {$reminderJoinClause}
1371 {$whereClause} {$limitWhereClause} AND {$repeatEventClause} {$originalEventStartDateClause} {$notINClause}
1375 $valsqlInsertValues = CRM_Core_DAO
::executeQuery($sqlInsertValues, array(
1377 $actionSchedule->id
,
1383 $arrValues = array();
1384 while ($valsqlInsertValues->fetch()) {
1385 $arrValues[] = "( {$valsqlInsertValues->contact_id}, {$valsqlInsertValues->entity_id}, '{$valsqlInsertValues->entity_table}',{$valsqlInsertValues->action_schedule_id} )";
1388 $valString = implode(',', $arrValues);
1392 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1393 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
1396 if ($isSendToAdditionalContacts) {
1397 $addSelect .= ', MAX(reminder.action_date_time) as latest_log_time';
1398 $sqlEndEventCheck = "
1399 SELECT * FROM {$table}
1400 {$whereClause} AND {$repeatEventClause} LIMIT 1";
1402 $daoCheck = CRM_Core_DAO
::executeQuery($sqlEndEventCheck);
1403 if ($daoCheck->fetch()) {
1404 $valSqlAdditionInsert = "
1406 FROM {$contactTable}
1408 INNER JOIN {$additionReminderClause}
1409 WHERE {$addWhere} AND c.is_deleted = 0 AND c.is_deceased = 0
1410 GROUP BY reminder.contact_id
1413 $daoForVals = CRM_Core_DAO
::executeQuery($valSqlAdditionInsert);
1414 $addValues = array();
1415 while ($daoForVals->fetch()) {
1416 $addValues[] = "( {$daoForVals->contact_id}, {$daoForVals->entity_id}, '{$daoForVals->entity_table}',{$daoForVals->action_schedule_id} )";
1418 $valString = implode(',', $addValues);
1422 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1423 CRM_Core_DAO
::executeQuery($query);
1434 * @return null|string
1436 public static function permissionedRelationships($field) {
1438 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
1439 FROM civicrm_membership m
1440 LEFT JOIN civicrm_membership cm ON cm.id = m.owner_membership_id
1441 LEFT JOIN civicrm_membership_type cmt ON cmt.id = m.membership_type_id
1442 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 )
1443 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 ) )
1444 WHERE m.owner_membership_id IS NOT NULL AND
1445 ( rel.is_permission_a_b = 0 OR rel.is_permission_b_a = 0)
1448 $excludeIds = array();
1449 $dao = CRM_Core_DAO
::executeQuery($query, array());
1450 while ($dao->fetch()) {
1451 if ($dao->slave_contact
== $dao->contact_id_a
&& $dao->is_permission_a_b
== 0) {
1452 $excludeIds[] = $dao->slave_contact
;
1454 elseif ($dao->slave_contact
== $dao->contact_id_b
&& $dao->is_permission_b_a
== 0) {
1455 $excludeIds[] = $dao->slave_contact
;
1459 if (!empty($excludeIds)) {
1460 $clause = "AND {$field} NOT IN ( " . implode(', ', $excludeIds) . ' ) ';
1468 * @param array $params
1472 public static function processQueue($now = NULL, $params = array()) {
1473 $now = $now ? CRM_Utils_Time
::setTime($now) : CRM_Utils_Time
::getTime();
1475 $mappings = self
::getMapping();
1476 foreach ($mappings as $mappingID => $mapping) {
1477 self
::buildRecipientContacts($mappingID, $now, $params);
1478 self
::sendMailings($mappingID, $now);
1483 'messages' => ts('Sent all scheduled reminders successfully'),
1490 * @param int $mappingID
1492 * @return null|string
1494 public static function isConfigured($id, $mappingID) {
1495 $queryString = "SELECT count(id) FROM civicrm_action_schedule
1496 WHERE mapping_id = %1 AND
1500 1 => array($mappingID, 'Integer'),
1501 2 => array($id, 'Integer'),
1503 return CRM_Core_DAO
::singleValueQuery($queryString, $params);
1507 * @param int $mappingID
1508 * @param $recipientType
1512 public static function getRecipientListing($mappingID, $recipientType) {
1514 if (!$mappingID ||
!$recipientType) {
1518 $mapping = self
::getMapping($mappingID);
1520 switch ($mapping['entity']) {
1521 case 'civicrm_participant':
1522 $eventContacts = CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
1523 if (empty($eventContacts[$recipientType])) {
1526 if ($eventContacts[$recipientType] == 'participant_role') {
1527 $options = CRM_Event_PseudoConstant
::participantRole();