3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
37 * This class contains functions for managing Scheduled Reminders
39 class CRM_Core_BAO_ActionSchedule
extends CRM_Core_DAO_ActionSchedule
{
46 public static function getMapping($id = NULL) {
47 static $_action_mapping;
49 if ($id && !is_null($_action_mapping) && isset($_action_mapping[$id])) {
50 return $_action_mapping[$id];
53 $dao = new CRM_Core_DAO_ActionMapping();
60 while ($dao->fetch()) {
62 CRM_Core_DAO
::storeValues($dao, $defaults);
63 $mapping[$dao->id
] = $defaults;
65 $_action_mapping = $mapping;
71 * Get all fields of the type Date.
73 public static function getDateFields() {
74 $allFields = CRM_Core_BAO_CustomField
::getFields('');
76 'birth_date' => ts('Birth Date'),
77 'created_date' => ts('Created Date'),
78 'modified_date' => ts('Modified Date'),
80 foreach ($allFields as $fieldID => $field) {
81 if ($field['data_type'] == 'Date') {
82 $dateFields["custom_$fieldID"] = $field['label'];
89 * Retrieve list of selections/drop downs for Scheduled Reminder form
95 * associated array of all the drop downs in the form
97 public static function getSelection($id = NULL) {
98 $mapping = CRM_Core_BAO_ActionSchedule
::getMapping();
99 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
100 $activityType = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE);
102 $participantStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label');
103 $event = CRM_Event_PseudoConstant
::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
104 $eventType = CRM_Event_PseudoConstant
::eventType();
105 $eventTemplate = CRM_Event_PseudoConstant
::eventTemplates();
106 $autoRenew = CRM_Core_OptionGroup
::values('auto_renew_options');
107 $membershipType = CRM_Member_PseudoConstant
::membershipType();
108 $dateFieldParams = array('data_type' => 'Date');
109 $dateFields = CRM_Core_BAO_ActionSchedule
::getDateFields();
110 $contactOptions = CRM_Core_OptionGroup
::values('contact_date_reminder_options');
112 asort($activityType);
114 $sel1 = $sel2 = $sel3 = $sel4 = $sel5 = array();
116 'manual' => ts('Choose Recipient(s)'),
117 'group' => ts('Select Group'),
120 $entityMapping = array();
121 $recipientMapping = array_combine(array_keys($options), array_keys($options));
127 foreach ($mapping as $value) {
128 $entityValue = CRM_Utils_Array
::value('entity_value', $value);
129 $entityStatus = CRM_Utils_Array
::value('entity_status', $value);
130 $entityRecipient = CRM_Utils_Array
::value('entity_recipient', $value);
131 $valueLabel = array('- ' . strtolower(CRM_Utils_Array
::value('entity_value_label', $value)) . ' -');
132 $key = CRM_Utils_Array
::value('id', $value);
133 $entityMapping[$key] = CRM_Utils_Array
::value('entity', $value);
136 switch ($entityValue) {
137 case 'activity_type':
138 if ($value['entity'] == 'civicrm_activity') {
139 $sel1Val = ts('Activity');
141 $sel2[$key] = $valueLabel +
$activityType;
145 if ($value['entity'] == 'civicrm_participant') {
146 $sel1Val = ts('Event Type');
148 $sel2[$key] = $valueLabel +
$eventType;
151 case 'event_template':
152 if ($value['entity'] == 'civicrm_participant') {
153 $sel1Val = ts('Event Template');
155 $sel2[$key] = $valueLabel +
$eventTemplate;
158 case 'civicrm_event':
159 if ($value['entity'] == 'civicrm_participant') {
160 $sel1Val = ts('Event Name');
162 $sel2[$key] = $valueLabel +
$event;
165 case 'civicrm_membership_type':
166 if ($value['entity'] == 'civicrm_membership') {
167 $sel1Val = ts('Membership');
169 $sel2[$key] = $valueLabel +
$membershipType;
172 case 'civicrm_contact':
173 if ($value['entity'] == 'civicrm_contact') {
174 $sel1Val = ts('Contact');
176 $sel2[$key] = $dateFields;
179 $sel1[$key] = $sel1Val;
182 if ($startDate = CRM_Utils_Array
::value('entity_date_start', $value)) {
183 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
185 if ($endDate = CRM_Utils_Array
::value('entity_date_end', $value)) {
186 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
189 switch ($entityRecipient) {
190 case 'activity_contacts':
191 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts');
192 $sel5[$entityRecipient] = $activityContacts +
$options;
193 $recipientMapping +
= CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
196 case 'event_contacts':
197 $eventContacts = CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name');
198 $sel5[$entityRecipient] = $eventContacts +
$options;
199 $recipientMapping +
= CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
203 $sel5[$entityRecipient] = $options;
210 foreach ($mapping as $value) {
211 $entityStatus = CRM_Utils_Array
::value('entity_status', $value);
212 $statusLabel = array('- ' . strtolower(CRM_Utils_Array
::value('entity_status_label', $value)) . ' -');
213 $id = CRM_Utils_Array
::value('id', $value);
215 switch ($entityStatus) {
216 case 'activity_status':
217 foreach ($sel3[$id] as $kkey => & $vval) {
218 $vval = $statusLabel +
$activityStatus;
222 case 'civicrm_participant_status_type':
223 foreach ($sel3[$id] as $kkey => & $vval) {
224 $vval = $statusLabel +
$participantStatus;
228 case 'auto_renew_options':
229 foreach ($sel3[$id] as $kkey => & $vval) {
232 $auto = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $kkey, 'auto_renew');
235 $vval = $statusLabel +
$autoRenew;
238 $vval = $statusLabel;
243 case 'contact_date_reminder_options':
244 foreach ($sel3[$id] as $kkey => & $vval) {
245 $vval = $contactOptions;
261 'entityMapping' => $entityMapping,
262 'recipientMapping' => $recipientMapping,
268 * @param int $isLimit
272 public static function getSelection1($id = NULL, $isLimit = NULL) {
273 $mapping = CRM_Core_BAO_ActionSchedule
::getMapping($id);
274 $sel4 = $sel5 = array();
276 'manual' => ts('Choose Recipient(s)'),
277 'group' => ts('Select Group'),
280 $recipientMapping = array_combine(array_keys($options), array_keys($options));
282 foreach ($mapping as $value) {
283 $entityRecipient = CRM_Utils_Array
::value('entity_recipient', $value);
284 $key = CRM_Utils_Array
::value('id', $value);
286 if ($startDate = CRM_Utils_Array
::value('entity_date_start', $value)) {
287 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
289 if ($endDate = CRM_Utils_Array
::value('entity_date_end', $value)) {
290 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
293 switch ($entityRecipient) {
294 case 'activity_contacts':
295 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts');
296 $sel5[$id] = $activityContacts +
$options;
297 $recipientMapping +
= CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
300 case 'event_contacts':
301 //CRM-15536, don't provide participant_role option on choosing 'Also Include' for Event entity
303 $options +
= CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name');
305 $sel5[$id] = $options;
306 $recipientMapping +
= CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
310 $sel5[$id] = $options;
317 'sel5' => $sel5[$id],
318 'recipientMapping' => $recipientMapping,
323 * Retrieve list of Scheduled Reminders.
325 * @param bool $namesOnly
326 * Return simple list of names.
328 * @param null $entityValue
332 * (reference) reminder list
334 public static function &getList($namesOnly = FALSE, $entityValue = NULL, $id = NULL) {
335 // These variables may appear unused, but there's some $$ stuff going on.
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 while ($actionSchedule->fetch()) {
698 if ($actionSchedule->from_email
) {
699 $fromEmailAddress = "$actionSchedule->from_name <$actionSchedule->from_email>";
702 list($tokenEntity, $tokenFields) = CRM_Core_BAO_ActionSchedule
::listMailingTokens($mapping);
703 $query = CRM_Core_BAO_ActionSchedule
::prepareMailingQuery($mapping, $actionSchedule);
704 $dao = CRM_Core_DAO
::executeQuery($query,
705 array(1 => array($actionSchedule->id
, 'Integer'))
708 $multilingual = CRM_Core_I18n
::isMultilingual();
709 while ($dao->fetch()) {
710 // switch language if necessary
712 $preferred_language = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $dao->contactID
, 'preferred_language');
713 CRM_Core_BAO_ActionSchedule
::setCommunicationLanguage($actionSchedule->communication_language
, $preferred_language);
716 $entityTokenParams = CRM_Core_BAO_ActionSchedule
::prepareMailingTokens($tokenEntity, $tokenFields, $dao);
719 $errorMsg = $toEmail = $toPhoneNumber = '';
721 if ($actionSchedule->mode
== 'SMS' or $actionSchedule->mode
== 'User_Preference') {
722 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
723 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($dao->contactID
, FALSE, 'Mobile', $filters);
724 //to get primary mobile ph,if not get a first mobile phONE
725 if (!empty($toPhoneNumbers)) {
726 $toPhoneNumberDetails = reset($toPhoneNumbers);
727 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumberDetails);
728 //contact allows to send sms
732 if ($actionSchedule->mode
== 'Email' or $actionSchedule->mode
== 'User_Preference') {
733 $toEmail = CRM_Contact_BAO_Contact
::getPrimaryEmail($dao->contactID
);
735 if ($toEmail ||
!(empty($toPhoneNumber) or $toDoNotSms)) {
736 $to['email'] = $toEmail;
737 $to['phone'] = $toPhoneNumber;
739 = CRM_Core_BAO_ActionSchedule
::sendReminder(
747 if (!$result ||
is_a($result, 'PEAR_Error')) {
748 // we could not send an email, for now we ignore, CRM-3406
754 $errorMsg = "Couldn\'t find recipient\'s email address.";
757 // update action log record
759 'id' => $dao->reminderID
,
760 'is_error' => $isError,
761 'message' => $errorMsg ?
$errorMsg : "null",
762 'action_date_time' => $now,
764 CRM_Core_BAO_ActionLog
::create($logParams);
766 // insert activity log record if needed
767 if ($actionSchedule->record_activity
&& !$isError) {
768 $caseID = empty($dao->case_id
) ?
NULL : $dao->case_id
;
769 CRM_Core_BAO_ActionSchedule
::createMailingActivity($actionSchedule, $mapping, $dao->contactID
, $dao->entityID
, $caseID);
778 * @param int $mappingID
780 * @param array $params
782 * @throws API_Exception
784 public static function buildRecipientContacts($mappingID, $now, $params = array()) {
785 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
786 $actionSchedule->mapping_id
= $mappingID;
787 $actionSchedule->is_active
= 1;
788 if (!empty($params)) {
789 _civicrm_api3_dao_set_filter($actionSchedule, $params, FALSE);
791 $actionSchedule->find();
793 while ($actionSchedule->fetch()) {
794 $mapping = new CRM_Core_DAO_ActionMapping();
795 $mapping->id
= $mappingID;
796 $mapping->find(TRUE);
798 // note: $where - this filtering applies for both
799 // 'limit to' and 'addition to' options
800 // $limitWhere - this filtering applies only for
802 $select = $join = $where = $limitWhere = array();
803 $selectColumns = "contact_id, entity_id, entity_table, action_schedule_id";
804 $limitTo = $actionSchedule->limit_to
;
805 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
806 trim($actionSchedule->entity_value
, CRM_Core_DAO
::VALUE_SEPARATOR
)
808 $value = implode(',', $value);
810 $status = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
811 trim($actionSchedule->entity_status
, CRM_Core_DAO
::VALUE_SEPARATOR
)
813 $status = implode(',', $status);
815 $anniversary = FALSE;
817 if (!CRM_Utils_System
::isNull($mapping->entity_recipient
)) {
818 if ($mapping->entity_recipient
== 'event_contacts') {
819 $recipientOptions = CRM_Core_OptionGroup
::values($mapping->entity_recipient
, FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
822 $recipientOptions = CRM_Core_OptionGroup
::values($mapping->entity_recipient
, FALSE, FALSE, FALSE, NULL, 'name');
825 $from = "{$mapping->entity} e";
827 if ($mapping->entity
== 'civicrm_activity') {
828 $contactField = 'r.contact_id';
829 $table = 'civicrm_activity e';
830 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
831 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
832 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
833 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
835 if (!is_null($limitTo)) {
837 // including the activity target contacts if 'in addition' is defined
838 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
841 switch (CRM_Utils_Array
::value($actionSchedule->recipient
, $recipientOptions)) {
842 case 'Activity Assignees':
843 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$assigneeID}";
846 case 'Activity Source':
847 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$sourceID}";
851 case 'Activity Targets':
852 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
857 // build where clause
858 if (!empty($value)) {
859 $where[] = "e.activity_type_id IN ({$value})";
862 $where[] = "e.activity_type_id IS NULL";
864 if (!empty($status)) {
865 $where[] = "e.status_id IN ({$status})";
867 $where[] = ' e.is_current_revision = 1 ';
868 $where[] = ' e.is_deleted = 0 ';
870 $dateField = 'e.activity_date_time';
873 if ($mapping->entity
== 'civicrm_participant') {
874 $table = 'civicrm_event r';
875 $contactField = 'e.contact_id';
876 $join[] = 'INNER JOIN civicrm_event r ON e.event_id = r.id';
877 if ($actionSchedule->recipient_listing
&& $limitTo) {
878 $rList = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
879 trim($actionSchedule->recipient_listing
, CRM_Core_DAO
::VALUE_SEPARATOR
)
881 $rList = implode(',', $rList);
883 switch (CRM_Utils_Array
::value($actionSchedule->recipient
, $recipientOptions)) {
884 case 'participant_role':
885 $where[] = "e.role_id IN ({$rList})";
893 // build where clause
894 if (!empty($value)) {
895 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IN ({$value})" : "r.id IN ({$value})";
898 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IS NULL" : "r.id IS NULL";
901 // participant status criteria not to be implemented
902 // for additional recipients
903 if (!empty($status)) {
904 $limitWhere[] = "e.status_id IN ({$status})";
907 $where[] = 'r.is_active = 1';
908 $where[] = 'r.is_template = 0';
909 $dateField = str_replace('event_', 'r.', $actionSchedule->start_action_date
);
913 if ($mapping->entity
== 'civicrm_membership') {
914 $contactField = 'e.contact_id';
915 $table = 'civicrm_membership e';
916 // build where clause
918 //auto-renew memberships
919 $where[] = "e.contribution_recur_id IS NOT NULL ";
921 elseif ($status == 1) {
922 $where[] = "e.contribution_recur_id IS NULL ";
925 // build where clause
926 if (!empty($value)) {
927 $where[] = "e.membership_type_id IN ({$value})";
930 $where[] = "e.membership_type_id IS NULL";
933 $where[] = "( e.is_override IS NULL OR e.is_override = 0 )";
934 $dateField = str_replace('membership_', 'e.', $actionSchedule->start_action_date
);
935 $notINClause = CRM_Core_BAO_ActionSchedule
::permissionedRelationships($contactField);
937 $membershipStatus = CRM_Member_PseudoConstant
::membershipStatus(NULL, "(is_current_member = 1 OR name = 'Expired')", 'id');
938 $mStatus = implode(',', $membershipStatus);
939 $where[] = "e.status_id IN ({$mStatus})";
941 // We are not tracking the reference date for 'repeated' schedule reminders,
942 // for further details please check CRM-15376
943 if ($actionSchedule->start_action_date
&& $actionSchedule->is_repeat
== FALSE) {
944 $select[] = $dateField;
945 $selectColumns = "reference_date, " . $selectColumns;
949 if ($mapping->entity
== 'civicrm_contact') {
950 $contactFields = array(
955 if (in_array($value, $contactFields)) {
956 $dateDBField = $value;
957 $table = 'civicrm_contact e';
958 $contactField = 'e.id';
959 $where[] = 'e.is_deleted = 0';
960 $where[] = 'e.is_deceased = 0';
964 $customFieldParams = array('id' => substr($value, 7));
965 $customGroup = $customField = array();
966 CRM_Core_BAO_CustomField
::retrieve($customFieldParams, $customField);
967 $dateDBField = $customField['column_name'];
968 $customGroupParams = array('id' => $customField['custom_group_id'], $customGroup);
969 CRM_Core_BAO_CustomGroup
::retrieve($customGroupParams, $customGroup);
970 $from = $table = "{$customGroup['table_name']} e";
971 $contactField = 'e.entity_id';
972 $where[] = '1'; // possible to have no "where" in this case
975 $status_ = explode(',', $status);
976 if (in_array(2, $status_)) {
978 $dateField = 'DATE_ADD(e.' . $dateDBField . ', INTERVAL ROUND(DATEDIFF(DATE(' . $now . '), e.' . $dateDBField . ') / 365) YEAR)';
983 $dateField = 'e.' . $dateDBField;
987 // CRM-13577 Introduce Smart Groups Handling
988 if ($actionSchedule->group_id
) {
990 // Need to check if its a smart group or not
991 // Then decide which table to join onto the query
992 $group = CRM_Contact_DAO_Group
::getTableName();
994 // Get the group information
996 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
998 WHERE $group.id = {$actionSchedule->group_id}
1001 $groupDAO = CRM_Core_DAO
::executeQuery($sql);
1002 $isSmartGroup = FALSE;
1004 $groupDAO->fetch() &&
1005 !empty($groupDAO->saved_search_id
)
1007 // Check that the group is in place in the cache and up to date
1008 CRM_Contact_BAO_GroupContactCache
::check($actionSchedule->group_id
);
1009 // Set smart group flag
1010 $isSmartGroup = TRUE;
1013 // CRM-13577 End Introduce Smart Groups Handling
1016 if ($actionSchedule->group_id
) {
1017 // CRM-13577 If smart group then use Cache table
1018 if ($isSmartGroup) {
1019 $join[] = "INNER JOIN civicrm_group_contact_cache grp ON {$contactField} = grp.contact_id";
1020 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1023 $join[] = "INNER JOIN civicrm_group_contact grp ON {$contactField} = grp.contact_id AND grp.status = 'Added'";
1024 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1027 elseif (!empty($actionSchedule->recipient_manual
)) {
1028 $rList = CRM_Utils_Type
::escape($actionSchedule->recipient_manual
, 'String');
1029 $where[] = "{$contactField} IN ({$rList})";
1032 elseif (!is_null($limitTo)) {
1033 $addGroup = $addWhere = '';
1034 if ($actionSchedule->group_id
) {
1035 // CRM-13577 If smart group then use Cache table
1036 if ($isSmartGroup) {
1037 $addGroup = " INNER JOIN civicrm_group_contact_cache grp ON c.id = grp.contact_id";
1038 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1041 $addGroup = " INNER JOIN civicrm_group_contact grp ON c.id = grp.contact_id AND grp.status = 'Added'";
1042 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1045 if (!empty($actionSchedule->recipient_manual
)) {
1046 $rList = CRM_Utils_Type
::escape($actionSchedule->recipient_manual
, 'String');
1047 $addWhere = "c.id IN ({$rList})";
1051 $select[] = "{$contactField} as contact_id";
1052 $select[] = 'e.id as entity_id';
1053 $select[] = "'{$mapping->entity}' as entity_table";
1054 $select[] = "{$actionSchedule->id} as action_schedule_id";
1055 $reminderJoinClause = "civicrm_action_log reminder ON reminder.contact_id = {$contactField} AND
1056 reminder.entity_id = e.id AND
1057 reminder.entity_table = '{$mapping->entity}' AND
1058 reminder.action_schedule_id = %1";
1061 // only consider reminders less than 11 months ago
1062 $reminderJoinClause .= " AND reminder.action_date_time > DATE_SUB({$now}, INTERVAL 11 MONTH)";
1065 if ($table != 'civicrm_contact e') {
1066 $join[] = "INNER JOIN civicrm_contact c ON c.id = {$contactField} AND c.is_deleted = 0 AND c.is_deceased = 0 ";
1069 $multilingual = CRM_Core_I18n
::isMultilingual();
1070 if ($multilingual && !empty($actionSchedule->filter_contact_language
)) {
1071 $tableAlias = ($table != 'civicrm_contact e') ?
'c' : 'e';
1073 // get language filter for the schedule
1074 $filter_contact_language = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $actionSchedule->filter_contact_language
);
1076 if (($key = array_search(CRM_Core_I18n
::NONE
, $filter_contact_language)) !== FALSE) {
1077 $w .= "{$tableAlias}.preferred_language IS NULL OR {$tableAlias}.preferred_language = '' OR ";
1078 unset($filter_contact_language[$key]);
1080 if (count($filter_contact_language) > 0) {
1081 $w .= "{$tableAlias}.preferred_language IN ('" . implode("','", $filter_contact_language) . "')";
1086 if ($actionSchedule->start_action_date
) {
1087 $startDateClause = array();
1088 $op = ($actionSchedule->start_action_condition
== 'before' ?
'<=' : '>=');
1089 $operator = ($actionSchedule->start_action_condition
== 'before' ?
'DATE_SUB' : 'DATE_ADD');
1090 $date = $operator . "({$dateField}, INTERVAL {$actionSchedule->start_action_offset} {$actionSchedule->start_action_unit})";
1091 $startDateClause[] = "'{$now}' >= {$date}";
1092 if ($mapping->entity
== 'civicrm_participant') {
1093 $startDateClause[] = $operator . "({$now}, INTERVAL 1 DAY ) {$op} " . $dateField;
1096 $startDateClause[] = "DATE_SUB({$now}, INTERVAL 1 DAY ) <= {$date}";
1099 $startDate = implode(' AND ', $startDateClause);
1101 elseif ($actionSchedule->absolute_date
) {
1102 $startDate = "DATEDIFF(DATE('{$now}'),'{$actionSchedule->absolute_date}') = 0";
1105 // ( now >= date_built_from_start_time ) OR ( now = absolute_date )
1106 $dateClause = "reminder.id IS NULL AND {$startDate}";
1108 // start composing query
1109 $selectClause = 'SELECT ' . implode(', ', $select);
1110 $fromClause = "FROM $from";
1111 $joinClause = !empty($join) ?
implode(' ', $join) : '';
1112 $whereClause = 'WHERE ' . implode(' AND ', $where);
1113 $limitWhereClause = '';
1114 if (!empty($limitWhere)) {
1115 $limitWhereClause = ' AND ' . implode(' AND ', $limitWhere);
1119 INSERT INTO civicrm_action_log ({$selectColumns})
1123 LEFT JOIN {$reminderJoinClause}
1124 {$whereClause} {$limitWhereClause} AND {$dateClause} {$notINClause}
1127 // In some cases reference_date got outdated due to many reason e.g. In Membership renewal end_date got extended
1128 // which means reference date mismatches with the end_date where end_date may be used as the start_action_date
1129 // criteria for some schedule reminder so in order to send new reminder we INSERT new reminder with new reference_date
1130 // value via UNION operation
1131 if (strpos($selectColumns, 'reference_date') !== FALSE) {
1132 $dateClause = str_replace('reminder.id IS NULL', 'reminder.id IS NOT NULL', $dateClause);
1134 INSERT INTO civicrm_action_log ({$selectColumns})
1138 LEFT JOIN {$reminderJoinClause}
1139 {$whereClause} {$limitWhereClause} {$notINClause} AND {$dateClause} AND
1140 reminder.action_date_time IS NOT NULL AND
1141 reminder.reference_date IS NOT NULL
1142 GROUP BY reminder.id, reminder.reference_date
1143 HAVING reminder.id = MAX(reminder.id) AND reminder.reference_date <> {$dateField}
1147 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
1149 if (!empty($referenceQuery)) {
1150 CRM_Core_DAO
::executeQuery($referenceQuery, array(1 => array($actionSchedule->id
, 'Integer')));
1153 $isSendToAdditionalContacts = (!is_null($limitTo) && $limitTo == 0 && (!empty($addGroup) ||
!empty($addWhere))) ?
TRUE : FALSE;
1154 if ($isSendToAdditionalContacts) {
1155 $contactTable = "civicrm_contact c";
1156 $addSelect = "SELECT c.id as contact_id, c.id as entity_id, 'civicrm_contact' as entity_table, {$actionSchedule->id} as action_schedule_id";
1157 $additionReminderClause = "civicrm_action_log reminder ON reminder.contact_id = c.id AND
1158 reminder.entity_id = c.id AND
1159 reminder.entity_table = 'civicrm_contact' AND
1160 reminder.action_schedule_id = {$actionSchedule->id}";
1161 $addWhereClause = '';
1163 $addWhereClause = "AND {$addWhere}";
1165 $insertAdditionalSql = "
1166 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1168 FROM ({$contactTable})
1169 LEFT JOIN {$additionReminderClause}
1171 WHERE c.is_deleted = 0 AND c.is_deceased = 0
1174 AND reminder.id IS NULL
1176 SELECT rem.contact_id
1177 FROM civicrm_action_log rem INNER JOIN {$mapping->entity} e ON rem.entity_id = e.id
1178 WHERE rem.action_schedule_id = {$actionSchedule->id}
1179 AND rem.entity_table = '{$mapping->entity}'
1183 CRM_Core_DAO
::executeQuery($insertAdditionalSql);
1185 // if repeat is turned ON:
1186 if ($actionSchedule->is_repeat
) {
1187 $repeatEvent = ($actionSchedule->end_action
== 'before' ?
'DATE_SUB' : 'DATE_ADD') . "({$dateField}, INTERVAL {$actionSchedule->end_frequency_interval} {$actionSchedule->end_frequency_unit})";
1189 if ($actionSchedule->repetition_frequency_unit
== 'day') {
1190 $interval = "{$actionSchedule->repetition_frequency_interval} DAY";
1192 elseif ($actionSchedule->repetition_frequency_unit
== 'week') {
1193 $interval = "{$actionSchedule->repetition_frequency_interval} WEEK";
1195 elseif ($actionSchedule->repetition_frequency_unit
== 'month') {
1196 $interval = "{$actionSchedule->repetition_frequency_interval} MONTH";
1198 elseif ($actionSchedule->repetition_frequency_unit
== 'year') {
1199 $interval = "{$actionSchedule->repetition_frequency_interval} YEAR";
1202 $interval = "{$actionSchedule->repetition_frequency_interval} HOUR";
1205 // (now <= repeat_end_time )
1206 $repeatEventClause = "'{$now}' <= {$repeatEvent}";
1207 // diff(now && logged_date_time) >= repeat_interval
1208 $havingClause = "HAVING TIMESTAMPDIFF(HOUR, latest_log_time, CAST({$now} AS datetime)) >= TIMESTAMPDIFF(HOUR, latest_log_time, DATE_ADD(latest_log_time, INTERVAL $interval))";
1209 $groupByClause = 'GROUP BY reminder.contact_id, reminder.entity_id, reminder.entity_table';
1210 $selectClause .= ', MAX(reminder.action_date_time) as latest_log_time';
1211 //CRM-15376 - do not send our reminders if original criteria no longer applies
1212 // the first part of the startDateClause array is the earliest the reminder can be sent. If the
1213 // event (e.g membership_end_date) has changed then the reminder may no longer apply
1214 // @todo - this only handles events that get moved later. Potentially they might get moved earlier
1215 $originalEventStartDateClause = empty($startDateClause) ?
'' : 'AND' . $startDateClause[0];
1216 $sqlInsertValues = "{$selectClause}
1219 INNER JOIN {$reminderJoinClause}
1220 {$whereClause} {$limitWhereClause} AND {$repeatEventClause} {$originalEventStartDateClause} {$notINClause}
1224 $valsqlInsertValues = CRM_Core_DAO
::executeQuery($sqlInsertValues, array(
1226 $actionSchedule->id
,
1232 $arrValues = array();
1233 while ($valsqlInsertValues->fetch()) {
1234 $arrValues[] = "( {$valsqlInsertValues->contact_id}, {$valsqlInsertValues->entity_id}, '{$valsqlInsertValues->entity_table}',{$valsqlInsertValues->action_schedule_id} )";
1237 $valString = implode(',', $arrValues);
1241 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1242 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
1245 if ($isSendToAdditionalContacts) {
1246 $addSelect .= ', MAX(reminder.action_date_time) as latest_log_time';
1247 $sqlEndEventCheck = "
1248 SELECT * FROM {$table}
1249 {$whereClause} AND {$repeatEventClause} LIMIT 1";
1251 $daoCheck = CRM_Core_DAO
::executeQuery($sqlEndEventCheck);
1252 if ($daoCheck->fetch()) {
1253 $valSqlAdditionInsert = "
1255 FROM {$contactTable}
1257 INNER JOIN {$additionReminderClause}
1258 WHERE {$addWhere} AND c.is_deleted = 0 AND c.is_deceased = 0
1259 GROUP BY reminder.contact_id
1262 $daoForVals = CRM_Core_DAO
::executeQuery($valSqlAdditionInsert);
1263 $addValues = array();
1264 while ($daoForVals->fetch()) {
1265 $addValues[] = "( {$daoForVals->contact_id}, {$daoForVals->entity_id}, '{$daoForVals->entity_table}',{$daoForVals->action_schedule_id} )";
1267 $valString = implode(',', $addValues);
1271 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1272 CRM_Core_DAO
::executeQuery($query);
1283 * @return null|string
1285 public static function permissionedRelationships($field) {
1287 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
1288 FROM civicrm_membership m
1289 LEFT JOIN civicrm_membership cm ON cm.id = m.owner_membership_id
1290 LEFT JOIN civicrm_membership_type cmt ON cmt.id = m.membership_type_id
1291 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 )
1292 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 ) )
1293 WHERE m.owner_membership_id IS NOT NULL AND
1294 ( rel.is_permission_a_b = 0 OR rel.is_permission_b_a = 0)
1297 $excludeIds = array();
1298 $dao = CRM_Core_DAO
::executeQuery($query, array());
1299 while ($dao->fetch()) {
1300 if ($dao->slave_contact
== $dao->contact_id_a
&& $dao->is_permission_a_b
== 0) {
1301 $excludeIds[] = $dao->slave_contact
;
1303 elseif ($dao->slave_contact
== $dao->contact_id_b
&& $dao->is_permission_b_a
== 0) {
1304 $excludeIds[] = $dao->slave_contact
;
1308 if (!empty($excludeIds)) {
1309 $clause = "AND {$field} NOT IN ( " . implode(', ', $excludeIds) . ' ) ';
1317 * @param array $params
1321 public static function processQueue($now = NULL, $params = array()) {
1322 $now = $now ? CRM_Utils_Time
::setTime($now) : CRM_Utils_Time
::getTime();
1324 $mappings = CRM_Core_BAO_ActionSchedule
::getMapping();
1325 foreach ($mappings as $mappingID => $mapping) {
1326 CRM_Core_BAO_ActionSchedule
::buildRecipientContacts($mappingID, $now, $params);
1327 CRM_Core_BAO_ActionSchedule
::sendMailings($mappingID, $now);
1332 'messages' => ts('Sent all scheduled reminders successfully'),
1339 * @param int $mappingID
1341 * @return null|string
1343 public static function isConfigured($id, $mappingID) {
1344 $queryString = "SELECT count(id) FROM civicrm_action_schedule
1345 WHERE mapping_id = %1 AND
1349 1 => array($mappingID, 'Integer'),
1350 2 => array($id, 'Integer'),
1352 return CRM_Core_DAO
::singleValueQuery($queryString, $params);
1356 * @param int $mappingID
1357 * @param $recipientType
1361 public static function getRecipientListing($mappingID, $recipientType) {
1363 if (!$mappingID ||
!$recipientType) {
1367 $mapping = CRM_Core_BAO_ActionSchedule
::getMapping($mappingID);
1369 switch ($mapping['entity']) {
1370 case 'civicrm_participant':
1371 $eventContacts = CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
1372 if (empty($eventContacts[$recipientType])) {
1375 if ($eventContacts[$recipientType] == 'participant_role') {
1376 $options = CRM_Event_PseudoConstant
::participantRole();
1385 * @param $communication_language
1386 * @param $preferred_language
1388 public static function setCommunicationLanguage($communication_language, $preferred_language) {
1389 $config = CRM_Core_Config
::singleton();
1390 $language = $config->lcMessages
;
1392 // prepare the language for the email
1393 if ($communication_language == CRM_Core_I18n
::AUTO
) {
1394 if (!empty($preferred_language)) {
1395 $language = $preferred_language;
1399 $language = $communication_language;
1402 // language not in the existing language, use default
1403 $languages = CRM_Core_I18n
::languages(TRUE);
1404 if (!in_array($language, $languages)) {
1405 $language = $config->lcMessages
;
1408 // change the language
1409 $i18n = CRM_Core_I18n
::singleton();
1410 $i18n->setLanguage($language);
1414 * Save a record about the delivery of a reminder email.
1416 * WISHLIST: Instead of saving $actionSchedule->body_html, call this immediately after
1417 * sending the message and pass in the fully rendered text of the message.
1419 * @param CRM_Core_DAO_ActionSchedule $actionSchedule
1420 * @param CRM_Core_DAO_ActionMapping $mapping
1421 * @param int $contactID
1422 * @param int $entityID
1423 * @param int|NULL $caseID
1424 * @throws CRM_Core_Exception
1426 protected static function createMailingActivity($actionSchedule, $mapping, $contactID, $entityID, $caseID) {
1427 $session = CRM_Core_Session
::singleton();
1429 if ($mapping->entity
== 'civicrm_membership') {
1431 = CRM_Core_OptionGroup
::getValue('activity_type', 'Membership Renewal Reminder', 'name');
1435 = CRM_Core_OptionGroup
::getValue('activity_type', 'Reminder Sent', 'name');
1438 $activityParams = array(
1439 'subject' => $actionSchedule->title
,
1440 'details' => $actionSchedule->body_html
,
1441 'source_contact_id' => $session->get('userID') ?
$session->get('userID') : $contactID,
1442 'target_contact_id' => $contactID,
1443 'activity_date_time' => CRM_Utils_Time
::getTime('YmdHis'),
1444 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
1445 'activity_type_id' => $activityTypeID,
1446 'source_record_id' => $entityID,
1448 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1450 //file reminder on case if source activity is a case activity
1451 if (!empty($caseID)) {
1452 $caseActivityParams = array();
1453 $caseActivityParams['case_id'] = $caseID;
1454 $caseActivityParams['activity_id'] = $activity->id
;
1455 CRM_Case_BAO_Case
::processCaseActivity($caseActivityParams);
1460 * @param $tokenEntity
1461 * @param $tokenFields
1465 protected static function prepareMailingTokens($tokenEntity, $tokenFields, $dao) {
1466 $entityTokenParams = array();
1467 foreach ($tokenFields as $field) {
1468 if ($field == 'location') {
1470 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
1471 $loc['street_address'] = $dao->street_address
;
1472 $loc['city'] = $dao->city
;
1473 $loc['state_province'] = CRM_Utils_Array
::value($dao->state_province_id
, $stateProvince);
1474 $loc['postal_code'] = $dao->postal_code
;
1475 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address
::format($loc);
1477 elseif ($field == 'info_url') {
1478 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
1480 elseif ($field == 'registration_url') {
1481 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
1483 elseif (in_array($field, array('start_date', 'end_date', 'join_date', 'activity_date_time'))) {
1484 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date
::customFormat($dao->$field);
1486 elseif ($field == 'balance') {
1487 if ($dao->entityTable
== 'civicrm_contact') {
1488 $balancePay = 'N/A';
1490 elseif (!empty($dao->entityID
)) {
1491 $info = CRM_Contribute_BAO_Contribution
::getPaymentInfo($dao->entityID
, 'event');
1492 $balancePay = CRM_Utils_Array
::value('balance', $info);
1493 $balancePay = CRM_Utils_Money
::format($balancePay);
1495 $entityTokenParams["{$tokenEntity}." . $field] = $balancePay;
1497 elseif ($field == 'fee_amount') {
1498 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Money
::format($dao->$field);
1501 $entityTokenParams["{$tokenEntity}." . $field] = $dao->$field;
1504 return $entityTokenParams;
1509 * @param $actionSchedule
1512 protected static function prepareMailingQuery($mapping, $actionSchedule) {
1513 $extraSelect = $extraJoin = $extraWhere = $extraOn = '';
1515 if ($mapping->entity
== 'civicrm_activity') {
1516 $compInfo = CRM_Core_Component
::getEnabledComponents();
1517 $extraSelect = ', ov.label as activity_type, e.id as activity_id';
1519 INNER JOIN civicrm_option_group og ON og.name = 'activity_type'
1520 INNER JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
1521 $extraOn = ' AND e.is_current_revision = 1 AND e.is_deleted = 0 ';
1522 if ($actionSchedule->limit_to
== 0) {
1524 LEFT JOIN civicrm_option_group og ON og.name = 'activity_type'
1525 LEFT JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
1529 // if CiviCase component is enabled
1530 if (array_key_exists('CiviCase', $compInfo)) {
1531 $extraSelect .= ", civicrm_case_activity.case_id as case_id";
1533 LEFT JOIN `civicrm_case_activity` ON `e`.`id` = `civicrm_case_activity`.`activity_id`";
1537 if ($mapping->entity
== 'civicrm_participant') {
1538 $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 ';
1541 INNER JOIN civicrm_event ev ON e.event_id = ev.id
1542 INNER JOIN civicrm_option_group og ON og.name = 'event_type'
1543 INNER JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
1544 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
1545 LEFT JOIN civicrm_address address ON address.id = lb.address_id
1546 LEFT JOIN civicrm_email email ON email.id = lb.email_id
1547 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
1549 if ($actionSchedule->limit_to
== 0) {
1551 LEFT JOIN civicrm_event ev ON e.event_id = ev.id
1552 LEFT JOIN civicrm_option_group og ON og.name = 'event_type'
1553 LEFT JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
1554 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
1555 LEFT JOIN civicrm_address address ON address.id = lb.address_id
1556 LEFT JOIN civicrm_email email ON email.id = lb.email_id
1557 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
1562 if ($mapping->entity
== 'civicrm_membership') {
1563 $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';
1565 INNER JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
1566 INNER JOIN civicrm_membership_status ms ON e.status_id = ms.id';
1568 if ($actionSchedule->limit_to
== 0) {
1570 LEFT JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
1571 LEFT JOIN civicrm_membership_status ms ON e.status_id = ms.id';
1575 $entityJoinClause = "INNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
1576 if ($actionSchedule->limit_to
== 0) {
1577 $entityJoinClause = "LEFT JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
1578 $extraWhere .= " AND (e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact')";
1580 $entityJoinClause .= $extraOn;
1583 SELECT reminder.id as reminderID, reminder.contact_id as contactID, reminder.entity_table as entityTable, reminder.*, e.id as entityID, e.* {$extraSelect}
1584 FROM civicrm_action_log reminder
1587 WHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL
1596 protected static function listMailingTokens($mapping) {
1597 $tokenEntity = NULL;
1598 $tokenFields = array();
1600 if ($mapping->entity
== 'civicrm_activity') {
1601 $tokenEntity = 'activity';
1602 $tokenFields = array('activity_id', 'activity_type', 'subject', 'details', 'activity_date_time');
1605 if ($mapping->entity
== 'civicrm_participant') {
1606 $tokenEntity = 'event';
1607 $tokenFields = array(
1625 if ($mapping->entity
== 'civicrm_membership') {
1626 $tokenEntity = 'membership';
1627 $tokenFields = array(
1638 if ($mapping->entity
== 'civicrm_contact') {
1639 $tokenEntity = 'contact';
1640 //TODO: get full list somewhere!
1641 $tokenFields = array('birth_date', 'last_name');
1642 //TODO: is there anything to add here?
1645 return array($tokenEntity, $tokenFields);