3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
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-2013
38 * This class contains functions for managing Scheduled Reminders
40 class CRM_Core_BAO_ActionSchedule
extends CRM_Core_DAO_ActionSchedule
{
42 static function getMapping($id = NULL) {
43 static $_action_mapping;
45 if ($id && !is_null($_action_mapping) && isset($_action_mapping[$id])) {
46 return $_action_mapping[$id];
49 $dao = new CRM_Core_DAO_ActionMapping();
56 while ($dao->fetch()) {
58 CRM_Core_DAO
::storeValues($dao, $defaults);
59 $mapping[$dao->id
] = $defaults;
61 $_action_mapping = $mapping;
67 * Retrieve list of selections/drop downs for Scheduled Reminder form
69 * @param bool $id mapping id
71 * @return array associated array of all the drop downs in the form
75 static function getSelection($id = NULL) {
76 $mapping = self
::getMapping($id);
77 $activityStatus = CRM_Core_PseudoConstant
::activityStatus();
78 $activityType = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE);
80 $participantStatus = CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label');
81 $event = CRM_Event_PseudoConstant
::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
82 $eventType = CRM_Event_PseudoConstant
::eventType();
83 $eventTemplate = CRM_Event_PseudoConstant
::eventTemplates();
84 $autoRenew = CRM_Core_OptionGroup
::values('auto_renew_options');
85 $membershipType = CRM_Member_PseudoConstant
::membershipType();
89 $sel1 = $sel2 = $sel3 = $sel4 = $sel5 = array();
91 'manual' => ts('Choose Recipient(s)'),
92 'group' => ts('Select a Group'),
95 $entityMapping = array();
96 $recipientMapping = array_combine(array_keys($options), array_keys($options));
102 foreach ($mapping as $value) {
103 $entityValue = CRM_Utils_Array
::value('entity_value', $value);
104 $entityStatus = CRM_Utils_Array
::value('entity_status', $value);
105 $entityRecipient = CRM_Utils_Array
::value('entity_recipient', $value);
106 $valueLabel = array('- ' . strtolower(CRM_Utils_Array
::value('entity_value_label', $value)) . ' -');
107 $key = CRM_Utils_Array
::value('id', $value);
108 $entityMapping[$key] = CRM_Utils_Array
::value('entity', $value);
111 switch ($entityValue) {
112 case 'activity_type':
113 if ($value['entity'] == 'civicrm_activity') {
114 $sel1Val = ts('Activity');
116 $sel2[$key] = $valueLabel +
$activityType;
120 if ($value['entity'] == 'civicrm_participant') {
121 $sel1Val = ts('Event Type');
123 $sel2[$key] = $valueLabel +
$eventType;
126 case 'event_template':
127 if ($value['entity'] == 'civicrm_participant') {
128 $sel1Val = ts('Event Template');
130 $sel2[$key] = $valueLabel +
$eventTemplate;
133 case 'civicrm_event':
134 if ($value['entity'] == 'civicrm_participant') {
135 $sel1Val = ts('Event Name');
137 $sel2[$key] = $valueLabel +
$event;
140 case 'civicrm_membership_type':
141 if ($value['entity'] == 'civicrm_membership') {
142 $sel1Val = ts('Membership');
144 $sel2[$key] = $valueLabel +
$membershipType;
147 $sel1[$key] = $sel1Val;
150 if ($startDate = CRM_Utils_Array
::value('entity_date_start', $value)) {
151 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
153 if ($endDate = CRM_Utils_Array
::value('entity_date_end', $value)) {
154 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
157 switch ($entityRecipient) {
158 case 'activity_contacts':
159 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts');
160 $sel5[$entityRecipient] = $activityContacts +
$options;
161 $recipientMapping +
= CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
164 case 'event_contacts':
165 $eventContacts = CRM_Core_OptionGroup
::values('event_contacts');
166 $sel5[$entityRecipient] = $eventContacts +
$options;
167 $recipientMapping +
= CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name');
171 $sel5[$entityRecipient] = $options;
178 foreach ($mapping as $value) {
179 $entityStatus = CRM_Utils_Array
::value('entity_status', $value);
180 $statusLabel = array('- ' . strtolower(CRM_Utils_Array
::value('entity_status_label', $value)) . ' -');
181 $id = CRM_Utils_Array
::value('id', $value);
183 switch ($entityStatus) {
184 case 'activity_status':
185 foreach ($sel3[$id] as $kkey => & $vval) {
186 $vval = $statusLabel +
$activityStatus;
190 case 'civicrm_participant_status_type':
191 foreach ($sel3[$id] as $kkey => & $vval) {
192 $vval = $statusLabel +
$participantStatus;
196 case 'auto_renew_options':
197 foreach ($sel3[$id] as $kkey => & $vval) {
200 $auto = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $kkey, 'auto_renew');
203 $vval = $statusLabel +
$autoRenew;
206 $vval = $statusLabel;
223 'entityMapping' => $entityMapping,
224 'recipientMapping' => $recipientMapping,
228 static function getSelection1($id = NULL) {
229 $mapping = self
::getMapping($id);
230 $sel4 = $sel5 = array();
232 'manual' => ts('Choose Recipient(s)'),
233 'group' => ts('Select a Group'),
236 $recipientMapping = array_combine(array_keys($options), array_keys($options));
238 foreach ($mapping as $value) {
239 $entityRecipient = CRM_Utils_Array
::value('entity_recipient', $value);
240 $key = CRM_Utils_Array
::value('id', $value);
242 if ($startDate = CRM_Utils_Array
::value('entity_date_start', $value)) {
243 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
245 if ($endDate = CRM_Utils_Array
::value('entity_date_end', $value)) {
246 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
249 switch ($entityRecipient) {
250 case 'activity_contacts':
251 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts');
252 $sel5[$id] = $activityContacts +
$options;
253 $recipientMapping +
= CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
256 case 'event_contacts':
257 $eventContacts = CRM_Core_OptionGroup
::values('event_contacts');
258 $sel5[$id] = $eventContacts +
$options;
259 $recipientMapping +
= CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name');
263 $sel5[$id] = $options;
270 'sel5' => $sel5[$id],
271 'recipientMapping' => $recipientMapping,
276 * Retrieve list of Scheduled Reminders
278 * @param bool $namesOnly return simple list of names
280 * @return array (reference) reminder list
284 static function &getList($namesOnly = FALSE, $entityValue = NULL, $id = NULL) {
285 $activity_type = CRM_Core_PseudoConstant
::activityType(FALSE) + CRM_Core_PseudoConstant
::activityType(FALSE, TRUE);
286 $activity_status = CRM_Core_PseudoConstant
::activityStatus();
288 $event_type = CRM_Event_PseudoConstant
::eventType();
289 $civicrm_event = CRM_Event_PseudoConstant
::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
290 $civicrm_participant_status_type = CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label');
291 $event_template = CRM_Event_PseudoConstant
::eventTemplates();
293 $auto_renew_options = CRM_Core_OptionGroup
::values('auto_renew_options');
294 $civicrm_membership_type = CRM_Member_PseudoConstant
::membershipType();
296 asort($activity_type);
298 'civicrm_activity' => 'Activity',
299 'civicrm_participant' => 'Event',
300 'civicrm_membership' => 'Member',
308 cam.entity_value as entityValue,
309 cas.entity_value as entityValueIds,
310 cam.entity_status as entityStatus,
311 cas.entity_status as entityStatusIds,
312 cas.start_action_date as entityDate,
313 cas.start_action_offset,
314 cas.start_action_unit,
315 cas.start_action_condition,
320 FROM civicrm_action_schedule cas
321 LEFT JOIN civicrm_action_mapping cam ON (cam.id = cas.mapping_id)
323 $params = CRM_Core_DAO
::$_nullArray;
325 if ($entityValue and $id) {
327 WHERE cas.entity_value = $id AND
328 cam.entity_value = '$entityValue'";
333 1 => array($id, 'Integer'),
334 2 => array($entityValue, 'String'),
338 $dao = CRM_Core_DAO
::executeQuery($query);
339 while ($dao->fetch()) {
340 $list[$dao->id
]['id'] = $dao->id
;
341 $list[$dao->id
]['title'] = $dao->title
;
342 $list[$dao->id
]['start_action_offset'] = $dao->start_action_offset
;
343 $list[$dao->id
]['start_action_unit'] = $dao->start_action_unit
;
344 $list[$dao->id
]['start_action_condition'] = $dao->start_action_condition
;
345 $list[$dao->id
]['entityDate'] = ucwords(str_replace('_', ' ', $dao->entityDate
));
346 $list[$dao->id
]['absolute_date'] = $dao->absolute_date
;
348 $status = $dao->entityStatus
;
349 $statusArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityStatusIds
);
350 foreach ($statusArray as & $s) {
351 $s = CRM_Utils_Array
::value($s, $
$status);
353 $statusIds = implode(', ', $statusArray);
355 $value = $dao->entityValue
;
356 $valueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityValueIds
);
357 foreach ($valueArray as & $v) {
358 $v = CRM_Utils_Array
::value($v, $
$value);
360 $valueIds = implode(', ', $valueArray);
361 $list[$dao->id
]['entity'] = $entity[$dao->entity
];
362 $list[$dao->id
]['value'] = $valueIds;
363 $list[$dao->id
]['status'] = $statusIds;
364 $list[$dao->id
]['is_repeat'] = $dao->is_repeat
;
365 $list[$dao->id
]['is_active'] = $dao->is_active
;
371 static function sendReminder($contactId, $to, $scheduleID, $from, $tokenParams) {
372 $email = $to['email'];
373 $phoneNumber = $to['phone'];
374 $schedule = new CRM_Core_DAO_ActionSchedule();
375 $schedule->id
= $scheduleID;
377 $domain = CRM_Core_BAO_Domain
::getDomain();
379 $hookTokens = array();
381 if ($schedule->find(TRUE)) {
382 $body_text = $schedule->body_text
;
383 $body_html = $schedule->body_html
;
384 $body_subject = $schedule->subject
;
386 $body_text = CRM_Utils_String
::htmlToText($body_html);
389 $params = array(array('contact_id', '=', $contactId, 0, 0));
390 list($contact, $_) = CRM_Contact_BAO_Query
::apiQuery($params);
393 $contact = reset($contact);
395 if (!$contact ||
is_a($contact, 'CRM_Core_Error')) {
399 // merge activity tokens with contact array
400 $contact = array_merge($contact, $tokenParams);
403 CRM_Utils_Hook
::tokenValues($contact, $contactId);
405 CRM_Utils_Hook
::tokens($hookTokens);
406 $categories = array_keys($hookTokens);
408 $type = array('html', 'text');
410 foreach ($type as $key => $value) {
411 $dummy_mail = new CRM_Mailing_BAO_Mailing();
412 $bodyType = "body_{$value}";
413 $dummy_mail->$bodyType = $
$bodyType;
414 $tokens = $dummy_mail->getTokens();
417 CRM_Utils_Token
::replaceGreetingTokens($
$bodyType, NULL, $contact['contact_id']);
418 $
$bodyType = CRM_Utils_Token
::replaceDomainTokens($
$bodyType, $domain, TRUE, $tokens[$value], TRUE);
419 $
$bodyType = CRM_Utils_Token
::replaceContactTokens($
$bodyType, $contact, FALSE, $tokens[$value], FALSE, TRUE);
420 $
$bodyType = CRM_Utils_Token
::replaceComponentTokens($
$bodyType, $contact, $tokens[$value], TRUE, FALSE);
421 $
$bodyType = CRM_Utils_Token
::replaceHookTokens($
$bodyType, $contact, $categories, TRUE);
427 $smarty = CRM_Core_Smarty
::singleton();
429 'text', 'html') as $elem) {
430 $
$elem = $smarty->fetch("string:{$$elem}");
434 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
440 $subjectToken = NULL;
442 foreach ($matches[1] as $token) {
443 list($type, $name) = preg_split('/\./', $token, 2);
445 if (!isset($subjectToken['contact'])) {
446 $subjectToken['contact'] = array();
448 $subjectToken['contact'][] = $name;
453 $messageSubject = CRM_Utils_Token
::replaceContactTokens($body_subject, $contact, FALSE, $subjectToken);
454 $messageSubject = CRM_Utils_Token
::replaceDomainTokens($messageSubject, $domain, TRUE, $tokens[$value]);
455 $messageSubject = CRM_Utils_Token
::replaceComponentTokens($messageSubject, $contact, $tokens[$value], TRUE);
456 $messageSubject = CRM_Utils_Token
::replaceHookTokens($messageSubject, $contact, $categories, TRUE);
458 $messageSubject = $smarty->fetch("string:{$messageSubject}");
460 if ($schedule->mode
== 'SMS' or $schedule->mode
== 'User_Preference') {
461 $session = CRM_Core_Session
::singleton();
462 $userID = $session->get('userID') ?
$session->get('userID') : $contactId;
463 $smsParams = array('To' => $phoneNumber, 'provider_id' => $schedule->sms_provider_id
, 'activity_subject' => $messageSubject);
464 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
468 $details = $html ?
$html : $text;
469 $activityParams = array(
470 'source_contact_id' => $userID,
471 'activity_type_id' => $activityTypeID,
472 'activity_date_time' => date('YmdHis'),
473 'subject' => $messageSubject,
474 'details' => $details,
475 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
478 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
480 CRM_Activity_BAO_Activity
::sendSMSMessage($contactId,
489 if ($schedule->mode
== 'Email' or $schedule->mode
== 'User_Preference') {
490 // set up the parameters for CRM_Utils_Mail::send
492 'groupName' => 'Scheduled Reminder Sender',
494 'toName' => $contact['display_name'],
496 'subject' => $messageSubject,
497 'entity' => 'action_schedule',
498 'entity_id' => $scheduleID,
501 if (!$html ||
$contact['preferred_mail_format'] == 'Text' ||
502 $contact['preferred_mail_format'] == 'Both'
504 // render the & entities in text mode, so that the links work
505 $mailParams['text'] = str_replace('&', '&', $text);
507 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
508 $contact['preferred_mail_format'] == 'Both'
511 $mailParams['html'] = $html;
513 $result = CRM_Utils_Mail
::send($mailParams);
522 * Function to add the schedules reminders in the db
524 * @param array $params (reference ) an assoc array of name/value pairs
525 * @param array $ids the array that holds all the db ids
527 * @return object CRM_Core_DAO_ActionSchedule
532 static function add(&$params, $ids = array()) {
533 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
534 $actionSchedule->copyValues($params);
536 return $actionSchedule->save();
540 * Takes a bunch of params that are needed to match certain criteria and
541 * retrieves the relevant objects. It also stores all the retrieved
542 * values in the default array
544 * @param array $params (reference ) an assoc array of name/value pairs
545 * @param array $values (reference ) an assoc array to hold the flattened values
547 * @return object CRM_Core_DAO_ActionSchedule object on success, null otherwise
551 static function retrieve(&$params, &$values) {
552 if (empty($params)) {
555 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
557 $actionSchedule->copyValues($params);
559 if ($actionSchedule->find(TRUE)) {
560 $ids['actionSchedule'] = $actionSchedule->id
;
562 CRM_Core_DAO
::storeValues($actionSchedule, $values);
564 return $actionSchedule;
570 * Function to delete a Reminder
572 * @param int $id ID of the Reminder to be deleted.
577 static function del($id) {
579 $dao = new CRM_Core_DAO_ActionSchedule();
581 if ($dao->find(TRUE)) {
586 CRM_Core_Error
::fatal(ts('Invalid value passed to delete function.'));
590 * update the is_active flag in the db
592 * @param int $id id of the database record
593 * @param boolean $is_active value we want to set the is_active field
595 * @return Object DAO object on success, null otherwise
598 static function setIsActive($id, $is_active) {
599 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
602 static function sendMailings($mappingID, $now) {
603 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
604 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
606 $mapping = new CRM_Core_DAO_ActionMapping();
607 $mapping->id
= $mappingID;
608 $mapping->find(TRUE);
610 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
611 $actionSchedule->mapping_id
= $mappingID;
612 $actionSchedule->is_active
= 1;
613 $actionSchedule->find(FALSE);
615 $tokenFields = array();
616 $session = CRM_Core_Session
::singleton();
618 while ($actionSchedule->fetch()) {
619 $extraSelect = $extraJoin = $extraWhere = $extraOn = '';
621 if ($actionSchedule->record_activity
) {
622 if ($mapping->entity
== 'civicrm_membership') {
624 CRM_Core_OptionGroup
::getValue('activity_type', 'Membership Renewal Reminder', 'name');
628 CRM_Core_OptionGroup
::getValue('activity_type', 'Reminder Sent', 'name');
632 CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
635 if ($mapping->entity
== 'civicrm_activity') {
636 $tokenEntity = 'activity';
637 $tokenFields = array('activity_id', 'activity_type', 'subject', 'details', 'activity_date_time');
638 $extraSelect = ', ov.label as activity_type, e.id as activity_id';
640 INNER JOIN civicrm_option_group og ON og.name = 'activity_type'
641 INNER JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
642 $extraOn = ' AND e.is_current_revision = 1 AND e.is_deleted = 0 ';
643 if ($actionSchedule->limit_to
== 0) {
645 LEFT JOIN civicrm_option_group og ON og.name = 'activity_type'
646 LEFT JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
650 if ($mapping->entity
== 'civicrm_participant') {
651 $tokenEntity = 'event';
652 $tokenFields = array('event_type', 'title', 'event_id', 'start_date', 'end_date', 'summary', 'description', 'location', 'info_url', 'registration_url', 'fee_amount', 'contact_email', 'contact_phone');
653 $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 ';
656 INNER JOIN civicrm_event ev ON e.event_id = ev.id
657 INNER JOIN civicrm_option_group og ON og.name = 'event_type'
658 INNER JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
659 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
660 LEFT JOIN civicrm_address address ON address.id = lb.address_id
661 LEFT JOIN civicrm_email email ON email.id = lb.email_id
662 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
664 if ($actionSchedule->limit_to
== 0) {
666 LEFT JOIN civicrm_event ev ON e.event_id = ev.id
667 LEFT JOIN civicrm_option_group og ON og.name = 'event_type'
668 LEFT JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
669 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
670 LEFT JOIN civicrm_address address ON address.id = lb.address_id
671 LEFT JOIN civicrm_email email ON email.id = lb.email_id
672 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
677 if ($mapping->entity
== 'civicrm_membership') {
678 $tokenEntity = 'membership';
679 $tokenFields = array('fee', 'id', 'join_date', 'start_date', 'end_date', 'status', 'type');
680 $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';
682 INNER JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
683 INNER JOIN civicrm_membership_status ms ON e.status_id = ms.id';
685 if ($actionSchedule->limit_to
== 0) {
687 LEFT JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
688 LEFT JOIN civicrm_membership_status ms ON e.status_id = ms.id';
692 $entityJoinClause = "INNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
693 if ($actionSchedule->limit_to
== 0) {
694 $entityJoinClause = "LEFT JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
695 $extraWhere .= " AND (e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact')";
697 $entityJoinClause .= $extraOn;
700 SELECT reminder.id as reminderID, reminder.contact_id as contactID, reminder.*, e.id as entityID, e.* {$extraSelect}
701 FROM civicrm_action_log reminder
704 WHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL
707 $dao = CRM_Core_DAO
::executeQuery($query,
708 array(1 => array($actionSchedule->id
, 'Integer'))
711 while ($dao->fetch()) {
712 $entityTokenParams = array();
713 foreach ($tokenFields as $field) {
714 if ($field == 'location') {
716 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
717 $loc['street_address'] = $dao->street_address
;
718 $loc['city'] = $dao->city
;
719 $loc['state_province'] = CRM_Utils_Array
::value($dao->state_province_id
, $stateProvince);
720 $loc['postal_code'] = $dao->postal_code
;
721 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address
::format($loc);
723 elseif ($field == 'info_url') {
724 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
726 elseif ($field == 'registration_url') {
727 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
729 elseif (in_array($field, array('start_date','end_date','join_date','activity_date_time'))) {
730 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date
::customFormat($dao->$field);
733 $entityTokenParams["{$tokenEntity}." . $field] = $dao->$field;
738 $errorMsg = $toEmail = $toPhoneNumber = '';
740 if ($actionSchedule->mode
== 'SMS' or $actionSchedule->mode
== 'User_Preference') {
741 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
742 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($dao->contactID
, FALSE, 'Mobile', $filters);
743 //to get primary mobile ph,if not get a first mobile phONE
744 if (!empty($toPhoneNumbers)) {
745 $toPhoneNumberDetails = reset($toPhoneNumbers);
746 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumberDetails);
747 //contact allows to send sms
751 if ($actionSchedule->mode
== 'Email' or $actionSchedule->mode
== 'User_Preference') {
752 $toEmail = CRM_Contact_BAO_Contact
::getPrimaryEmail($dao->contactID
);
754 if ($toEmail ||
!(empty($toPhoneNumber) or $toDoNotSms)) {
755 $to['email'] = $toEmail;
756 $to['phone'] = $toPhoneNumber;
758 CRM_Core_BAO_ActionSchedule
::sendReminder(
766 if (!$result ||
is_a($result, 'PEAR_Error')) {
767 // we could not send an email, for now we ignore, CRM-3406
773 $errorMsg = "Couldn\'t find recipient\'s email address.";
776 // update action log record
778 'id' => $dao->reminderID
,
779 'is_error' => $isError,
780 'message' => $errorMsg ?
$errorMsg : "null",
781 'action_date_time' => $now,
783 CRM_Core_BAO_ActionLog
::create($logParams);
785 // insert activity log record if needed
786 if ($actionSchedule->record_activity
) {
787 $activityParams = array(
788 'subject' => $actionSchedule->title
,
789 'details' => $actionSchedule->body_html
,
790 'source_contact_id' =>
791 $session->get('userID') ?
$session->get('userID') : $dao->contactID
,
792 'target_contact_id' => $dao->contactID
,
793 'activity_date_time' => date('YmdHis'),
794 'status_id' => $activityStatusID,
795 'activity_type_id' => $activityTypeID,
796 'source_record_id' => $dao->entityID
,
798 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
806 static function buildRecipientContacts($mappingID, $now) {
807 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
808 $actionSchedule->mapping_id
= $mappingID;
809 $actionSchedule->is_active
= 1;
810 $actionSchedule->find();
812 while ($actionSchedule->fetch()) {
813 $mapping = new CRM_Core_DAO_ActionMapping();
814 $mapping->id
= $mappingID;
815 $mapping->find(TRUE);
817 // note: $where - this filtering applies for both
818 // 'limit to' and 'addition to' options
819 // $limitWhere - this filtering applies only for
821 $select = $join = $where = $limitWhere = array();
822 $limitTo = $actionSchedule->limit_to
;
823 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
824 trim($actionSchedule->entity_value
, CRM_Core_DAO
::VALUE_SEPARATOR
)
826 $value = implode(',', $value);
828 $status = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
829 trim($actionSchedule->entity_status
, CRM_Core_DAO
::VALUE_SEPARATOR
)
831 $status = implode(',', $status);
833 if (!CRM_Utils_System
::isNull($mapping->entity_recipient
)) {
834 $recipientOptions = CRM_Core_OptionGroup
::values($mapping->entity_recipient
, FALSE, FALSE, FALSE, NULL, 'name');
836 $from = "{$mapping->entity} e";
838 if ($mapping->entity
== 'civicrm_activity') {
839 $contactField = 'r.contact_id';
840 $table = 'civicrm_activity e';
841 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
842 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
843 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
844 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
847 // including the activity target contacts if 'in addition' is defined
848 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
851 switch (CRM_Utils_Array
::value($actionSchedule->recipient
, $recipientOptions)) {
852 case 'Activity Assignees':
853 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$assigneeID}";
856 case 'Activity Source':
857 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$sourceID}";
861 case 'Activity Targets':
862 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
866 // build where clause
867 if (!empty($value)) {
868 $where[] = "e.activity_type_id IN ({$value})";
871 $where[] = "e.activity_type_id IS NULL";
873 if (!empty($status)) {
874 $where[] = "e.status_id IN ({$status})";
876 $where[] = ' e.is_current_revision = 1 ';
877 $where[] = ' e.is_deleted = 0 ';
879 $dateField = 'e.activity_date_time';
882 if ($mapping->entity
== 'civicrm_participant') {
883 $table = 'civicrm_event r';
884 $contactField = 'e.contact_id';
885 $join[] = 'INNER JOIN civicrm_event r ON e.event_id = r.id';
886 if ($actionSchedule->recipient_listing
&& $limitTo) {
887 $rList = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
888 trim($actionSchedule->recipient_listing
, CRM_Core_DAO
::VALUE_SEPARATOR
)
890 $rList = implode(',', $rList);
892 switch ($recipientOptions[$actionSchedule->recipient
]) {
893 case 'participant_role':
894 $where[] = "e.role_id IN ({$rList})";
902 // build where clause
903 if (!empty($value)) {
904 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IN ({$value})" : "r.id IN ({$value})";
907 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IS NULL" : "r.id IS NULL";
910 // participant status criteria not to be implemented
911 // for additional recipients
912 if (!empty($status)) {
913 $limitWhere[] = "e.status_id IN ({$status})";
916 $where[] = 'r.is_active = 1';
917 $where[] = 'r.is_template = 0';
918 $dateField = str_replace('event_', 'r.', $actionSchedule->start_action_date
);
922 if ($mapping->entity
== 'civicrm_membership') {
923 $contactField = 'e.contact_id';
924 $table = 'civicrm_membership e';
925 // build where clause
926 if ( $status == 2 ) {
927 //auto-renew memberships
928 $where[] = "e.contribution_recur_id IS NOT NULL ";
930 elseif ( $status == 1 ) {
931 $where[] = "e.contribution_recur_id IS NULL ";
934 // build where clause
935 if (!empty($value)) {
936 $where[] = "e.membership_type_id IN ({$value})";
939 $where[] = "e.membership_type_id IS NULL";
942 $where[] = "( e.is_override IS NULL OR e.is_override = 0 )";
943 $dateField = str_replace('membership_', 'e.', $actionSchedule->start_action_date
);
944 $notINClause = self
::permissionedRelationships($contactField);
946 $membershipStatus = CRM_Member_PseudoConstant
::membershipStatus(NULL, "(is_current_member = 1 OR name = 'Expired')", 'id');
947 $mStatus = implode (',', $membershipStatus);
948 $where[] = "e.status_id IN ({$mStatus})";
951 // CRM-13577 Introduce Smart Groups Handling
952 if ($actionSchedule->group_id
) {
954 // Need to check if its a smart group or not
955 // Then decide which table to join onto the query
956 $group = CRM_Contact_DAO_Group
::getTableName();
958 // Get the group information
960 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
962 WHERE $group.id = {$actionSchedule->group_id}
965 $groupDAO = CRM_Core_DAO
::executeQuery($sql);
966 $isSmartGroup = FALSE;
968 $groupDAO->fetch() &&
969 !empty($groupDAO->saved_search_id
)
971 // Check that the group is in place in the cache and up to date
972 CRM_Contact_BAO_GroupContactCache
::check($actionSchedule->group_id
);
973 // Set smart group flag
974 $isSmartGroup = TRUE;
977 // CRM-13577 End Introduce Smart Groups Handling
980 if ($actionSchedule->group_id
) {
981 // CRM-13577 If smart group then use Cache table
983 $join[] = "INNER JOIN civicrm_group_contact_cache grp ON {$contactField} = grp.contact_id";
984 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
986 $join[] = "INNER JOIN civicrm_group_contact grp ON {$contactField} = grp.contact_id AND grp.status = 'Added'";
987 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
990 elseif (!empty($actionSchedule->recipient_manual
)) {
991 $rList = CRM_Utils_Type
::escape($actionSchedule->recipient_manual
, 'String');
992 $where[] = "{$contactField} IN ({$rList})";
996 $addGroup = $addWhere = '';
997 if ($actionSchedule->group_id
) {
998 // CRM-13577 If smart group then use Cache table
1000 $addGroup = " INNER JOIN civicrm_group_contact_cache grp ON c.id = grp.contact_id";
1001 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1003 $addGroup = " INNER JOIN civicrm_group_contact grp ON c.id = grp.contact_id AND grp.status = 'Added'";
1004 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1007 if (!empty($actionSchedule->recipient_manual
)) {
1008 $rList = CRM_Utils_Type
::escape($actionSchedule->recipient_manual
, 'String');
1009 $addWhere = "c.id IN ({$rList})";
1013 $select[] = "{$contactField} as contact_id";
1014 $select[] = 'e.id as entity_id';
1015 $select[] = "'{$mapping->entity}' as entity_table";
1016 $select[] = "{$actionSchedule->id} as action_schedule_id";
1017 $reminderJoinClause = "civicrm_action_log reminder ON reminder.contact_id = {$contactField} AND
1018 reminder.entity_id = e.id AND
1019 reminder.entity_table = '{$mapping->entity}' AND
1020 reminder.action_schedule_id = %1";
1022 $join[] = "INNER JOIN civicrm_contact c ON c.id = {$contactField} AND c.is_deleted = 0 AND c.is_deceased = 0 ";
1024 if ($actionSchedule->start_action_date
) {
1025 $startDateClause = array();
1026 $op = ($actionSchedule->start_action_condition
== 'before' ?
'<=' : '>=');
1027 $operator = ($actionSchedule->start_action_condition
== 'before' ?
'DATE_SUB' : 'DATE_ADD');
1028 $date = $operator . "({$dateField}, INTERVAL {$actionSchedule->start_action_offset} {$actionSchedule->start_action_unit})";
1029 $startDateClause[] = "'{$now}' >= {$date}";
1030 if ($mapping->entity
== 'civicrm_participant') {
1031 $startDateClause[] = $operator. "({$now}, INTERVAL 1 DAY ) {$op} " . $dateField;
1034 $startDateClause[] = "DATE_SUB({$now}, INTERVAL 1 DAY ) <= {$date}";
1037 $startDate = implode(' AND ', $startDateClause);
1039 elseif ($actionSchedule->absolute_date
) {
1040 $startDate = "DATEDIFF(DATE('{$now}'),'{$actionSchedule->absolute_date}') = 0";
1043 // ( now >= date_built_from_start_time ) OR ( now = absolute_date )
1044 $dateClause = "reminder.id IS NULL AND {$startDate}";
1046 // start composing query
1047 $selectClause = 'SELECT ' . implode(', ', $select);
1048 $fromClause = "FROM $from";
1049 $joinClause = !empty($join) ?
implode(' ', $join) : '';
1050 $whereClause = 'WHERE ' . implode(' AND ', $where);
1051 $limitWhereClause = '';
1052 if (!empty($limitWhere)) {
1053 $limitWhereClause = ' AND ' . implode(' AND ', $limitWhere);
1057 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1061 LEFT JOIN {$reminderJoinClause}
1062 {$whereClause} {$limitWhereClause} AND {$dateClause} {$notINClause}
1064 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
1066 if ($limitTo == 0) {
1067 $additionWhere = ' WHERE ';
1068 if ($actionSchedule->start_action_date
) {
1069 $additionWhere = $whereClause . ' AND ';
1071 $contactTable = "civicrm_contact c";
1072 $addSelect = "SELECT c.id as contact_id, c.id as entity_id, 'civicrm_contact' as entity_table, {$actionSchedule->id} as action_schedule_id";
1073 $additionReminderClause = "civicrm_action_log reminder ON reminder.contact_id = c.id AND
1074 reminder.entity_id = c.id AND
1075 reminder.entity_table = 'civicrm_contact' AND
1076 reminder.action_schedule_id = {$actionSchedule->id}";
1077 $addWhereClause = '';
1079 $addWhereClause = "AND {$addWhere}";
1081 $insertAdditionalSql ="
1082 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1084 FROM ({$contactTable}, {$table})
1085 LEFT JOIN {$additionReminderClause}
1087 {$additionWhere} c.is_deleted = 0 AND c.is_deceased = 0
1091 SELECT rem.contact_id
1092 FROM civicrm_action_log rem INNER JOIN {$mapping->entity} e ON rem.entity_id = e.id
1093 WHERE rem.action_schedule_id = {$actionSchedule->id}
1094 AND rem.entity_table = '{$mapping->entity}'
1098 CRM_Core_DAO
::executeQuery($insertAdditionalSql);
1100 // if repeat is turned ON:
1101 if ($actionSchedule->is_repeat
) {
1102 $repeatEvent = ($actionSchedule->end_action
== 'before' ?
'DATE_SUB' : 'DATE_ADD') . "({$dateField}, INTERVAL {$actionSchedule->end_frequency_interval} {$actionSchedule->end_frequency_unit})";
1104 if ($actionSchedule->repetition_frequency_unit
== 'day') {
1105 $hrs = 24 * $actionSchedule->repetition_frequency_interval
;
1107 elseif ($actionSchedule->repetition_frequency_unit
== 'week') {
1108 $hrs = 24 * $actionSchedule->repetition_frequency_interval
* 7;
1111 $hrs = $actionSchedule->repetition_frequency_interval
;
1114 // (now <= repeat_end_time )
1115 $repeatEventClause = "'{$now}' <= {$repeatEvent}";
1116 // diff(now && logged_date_time) >= repeat_interval
1117 $havingClause = "HAVING TIMEDIFF({$now}, latest_log_time) >= TIME('{$hrs}:00:00')";
1118 $groupByClause = 'GROUP BY reminder.contact_id, reminder.entity_id, reminder.entity_table';
1119 $selectClause .= ', MAX(reminder.action_date_time) as latest_log_time';
1120 $sqlInsertValues = "{$selectClause}
1123 INNER JOIN {$reminderJoinClause}
1124 {$whereClause} {$limitWhereClause} AND {$repeatEventClause}
1128 $valsqlInsertValues = CRM_Core_DAO
::executeQuery($sqlInsertValues, array(1 => array($actionSchedule->id
, 'Integer')));
1130 $arrValues = array();
1131 while ($valsqlInsertValues->fetch()) {
1132 $arrValues[] = "( {$valsqlInsertValues->contact_id}, {$valsqlInsertValues->entity_id}, '{$valsqlInsertValues->entity_table}',{$valsqlInsertValues->action_schedule_id} )";
1135 $valString = implode(',', $arrValues);
1139 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1140 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
1143 if ($limitTo == 0) {
1144 $addSelect .= ', MAX(reminder.action_date_time) as latest_log_time';
1145 $sqlEndEventCheck = "
1146 SELECT * FROM {$table}
1147 {$whereClause} AND {$repeatEventClause} LIMIT 1";
1149 $daoCheck = CRM_Core_DAO
::executeQuery($sqlEndEventCheck);
1150 if ($daoCheck->fetch()) {
1151 $valSqlAdditionInsert = "
1153 FROM {$contactTable}
1155 INNER JOIN {$additionReminderClause}
1156 WHERE {$addWhere} AND c.is_deleted = 0 AND c.is_deceased = 0
1157 GROUP BY reminder.contact_id
1160 $daoForVals = CRM_Core_DAO
::executeQuery($valSqlAdditionInsert);
1161 $addValues = array();
1162 while ($daoForVals->fetch()) {
1163 $addValues[] = "( {$daoForVals->contact_id}, {$daoForVals->entity_id}, '{$daoForVals->entity_table}',{$daoForVals->action_schedule_id} )";
1165 $valString = implode(',', $addValues);
1169 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1170 CRM_Core_DAO
::executeQuery($query);
1178 static function permissionedRelationships($field) {
1180 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
1181 FROM civicrm_membership m
1182 LEFT JOIN civicrm_membership cm ON cm.id = m.owner_membership_id
1183 LEFT JOIN civicrm_membership_type cmt ON cmt.id = m.membership_type_id
1184 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 )
1185 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 ) )
1186 WHERE m.owner_membership_id IS NOT NULL AND
1187 ( rel.is_permission_a_b = 0 OR rel.is_permission_b_a = 0)
1190 $excludeIds = array();
1191 $dao = CRM_Core_DAO
::executeQuery($query, array());
1192 while ($dao->fetch()) {
1193 if ($dao->slave_contact
== $dao->contact_id_a
&& $dao->is_permission_b_a
== 0) {
1194 $excludeIds[] = $dao->slave_contact
;
1196 elseif ($dao->slave_contact
== $dao->contact_id_b
&& $dao->is_permission_a_b
== 0) {
1197 $excludeIds[] = $dao->slave_contact
;
1201 if (!empty($excludeIds)) {
1202 $clause = "AND {$field} NOT IN ( " .implode(', ', $excludeIds) . ' ) ';
1208 static function processQueue($now = NULL) {
1209 $now = $now ? CRM_Utils_Time
::setTime($now) : CRM_Utils_Time
::getTime();
1211 $mappings = self
::getMapping();
1212 foreach ($mappings as $mappingID => $mapping) {
1213 self
::buildRecipientContacts($mappingID, $now);
1214 self
::sendMailings($mappingID, $now);
1219 'messages' => ts('Sent all scheduled reminders successfully'),
1224 static function isConfigured($id, $mappingID) {
1225 $queryString = "SELECT count(id) FROM civicrm_action_schedule
1226 WHERE mapping_id = %1 AND
1230 1 => array($mappingID, 'Integer'),
1231 2 => array($id, 'Integer'),
1233 return CRM_Core_DAO
::singleValueQuery($queryString, $params);
1236 static function getRecipientListing($mappingID, $recipientType) {
1238 if (!$mappingID ||
!$recipientType) {
1242 $mapping = self
::getMapping($mappingID);
1244 switch ($mapping['entity']) {
1245 case 'civicrm_participant':
1246 $eventContacts = CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1247 if (empty($eventContacts[$recipientType])) {
1250 if ($eventContacts[$recipientType] == 'participant_role') {
1251 $options = CRM_Event_PseudoConstant
::participantRole();