3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
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(FALSE) + CRM_Core_PseudoConstant
::activityType(FALSE, 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_PseudoConstant
::autoRenew();
85 $membershipType = CRM_Member_PseudoConstant
::membershipType();
89 $sel1 = $sel2 = $sel3 = $sel4 = $sel5 = array();
90 $options = array('manual' => ts('Choose Recipient(s)'),
91 'group' => ts('Select a Group'),
94 $entityMapping = array();
95 $recipientMapping = array_combine(array_keys($options), array_keys($options));
101 foreach ($mapping as $value) {
102 $entityValue = CRM_Utils_Array
::value('entity_value', $value);
103 $entityStatus = CRM_Utils_Array
::value('entity_status', $value);
104 $entityRecipient = CRM_Utils_Array
::value('entity_recipient', $value);
105 $valueLabel = array('- ' . strtolower(CRM_Utils_Array
::value('entity_value_label', $value)) . ' -');
106 $key = CRM_Utils_Array
::value('id', $value);
107 $entityMapping[$key] = CRM_Utils_Array
::value('entity', $value);
110 switch ($entityValue) {
111 case 'activity_type':
112 if ($value['entity'] == 'civicrm_activity') {
113 $sel1Val = ts('Activity');
115 $sel2[$key] = $valueLabel +
$activityType;
119 if ($value['entity'] == 'civicrm_participant') {
120 $sel1Val = ts('Event Type');
122 $sel2[$key] = $valueLabel +
$eventType;
125 case 'event_template':
126 if ($value['entity'] == 'civicrm_participant') {
127 $sel1Val = ts('Event Template');
129 $sel2[$key] = $valueLabel +
$eventTemplate;
132 case 'civicrm_event':
133 if ($value['entity'] == 'civicrm_participant') {
134 $sel1Val = ts('Event Name');
136 $sel2[$key] = $valueLabel +
$event;
139 case 'civicrm_membership_type':
140 if ($value['entity'] == 'civicrm_membership') {
141 $sel1Val = ts('Membership');
143 $sel2[$key] = $valueLabel +
$membershipType;
146 $sel1[$key] = $sel1Val;
149 if ($startDate = CRM_Utils_Array
::value('entity_date_start', $value)) {
150 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
152 if ($endDate = CRM_Utils_Array
::value('entity_date_end', $value)) {
153 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
156 switch ($entityRecipient) {
157 case 'activity_contacts':
158 $activityContacts = CRM_Core_PseudoConstant
::activityContacts();
159 $sel5[$entityRecipient] = $activityContacts +
$options;
160 $recipientMapping +
= CRM_Core_PseudoConstant
::activityContacts('name');
163 case 'event_contacts':
164 $eventContacts = CRM_Core_PseudoConstant
::eventContacts();
165 $sel5[$entityRecipient] = $eventContacts +
$options;
166 $recipientMapping +
= CRM_Core_PseudoConstant
::eventContacts('name');
170 $sel5[$entityRecipient] = $options;
177 foreach ($mapping as $value) {
178 $entityStatus = CRM_Utils_Array
::value('entity_status', $value);
179 $statusLabel = array('- ' . strtolower(CRM_Utils_Array
::value('entity_status_label', $value)) . ' -');
180 $id = CRM_Utils_Array
::value('id', $value);
182 switch ($entityStatus) {
183 case 'activity_status':
184 foreach ($sel3[$id] as $kkey => & $vval) {
185 $vval = $statusLabel +
$activityStatus;
189 case 'civicrm_participant_status_type':
190 foreach ($sel3[$id] as $kkey => & $vval) {
191 $vval = $statusLabel +
$participantStatus;
195 case 'auto_renew_options':
196 foreach ($sel3[$id] as $kkey => & $vval) {
199 $auto = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $kkey, 'auto_renew');
202 $vval = $statusLabel +
$autoRenew;
205 $vval = $statusLabel;
223 'entityMapping' => $entityMapping,
224 'recipientMapping' => $recipientMapping,
228 static function getSelection1($id = NULL) {
229 $mapping = self
::getMapping($id);
230 $sel4 = $sel5 = array();
231 $options = array('manual' => ts('Choose Recipient(s)'),
232 'group' => ts('Select a Group'),
235 $recipientMapping = array_combine(array_keys($options), array_keys($options));
237 foreach ($mapping as $value) {
238 $entityRecipient = CRM_Utils_Array
::value('entity_recipient', $value);
239 $key = CRM_Utils_Array
::value('id', $value);
241 if ($startDate = CRM_Utils_Array
::value('entity_date_start', $value)) {
242 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
244 if ($endDate = CRM_Utils_Array
::value('entity_date_end', $value)) {
245 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
248 switch ($entityRecipient) {
249 case 'activity_contacts':
250 $activityContacts = CRM_Core_PseudoConstant
::activityContacts();
251 $sel5[$id] = $activityContacts +
$options;
252 $recipientMapping +
= CRM_Core_PseudoConstant
::activityContacts('name');
255 case 'event_contacts':
256 $eventContacts = CRM_Core_PseudoConstant
::eventContacts();
257 $sel5[$id] = $eventContacts +
$options;
258 $recipientMapping +
= CRM_Core_PseudoConstant
::eventContacts('name');
262 $sel5[$id] = $options;
269 'sel5' => $sel5[$id],
270 'recipientMapping' => $recipientMapping,
275 * Retrieve list of Scheduled Reminders
277 * @param bool $namesOnly return simple list of names
279 * @return array (reference) reminder list
283 static function &getList($namesOnly = FALSE, $entityValue = NULL, $id = NULL) {
284 $activity_type = CRM_Core_PseudoConstant
::activityType(FALSE) + CRM_Core_PseudoConstant
::activityType(FALSE, TRUE);
285 $activity_status = CRM_Core_PseudoConstant
::activityStatus();
287 $event_type = CRM_Event_PseudoConstant
::eventType();
288 $civicrm_event = CRM_Event_PseudoConstant
::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
289 $civicrm_participant_status_type = CRM_Event_PseudoConstant
::participantStatus(NULL, NULL, 'label');
290 $event_template = CRM_Event_PseudoConstant
::eventTemplates();
292 $auto_renew_options = CRM_Core_PseudoConstant
::autoRenew();
293 $civicrm_membership_type = CRM_Member_PseudoConstant
::membershipType();
295 asort($activity_type);
297 'civicrm_activity' => 'Activity',
298 'civicrm_participant' => 'Event',
299 'civicrm_membership' => 'Member',
307 cam.entity_value as entityValue,
308 cas.entity_value as entityValueIds,
309 cam.entity_status as entityStatus,
310 cas.entity_status as entityStatusIds,
311 cas.start_action_date as entityDate,
312 cas.start_action_offset,
313 cas.start_action_unit,
314 cas.start_action_condition,
319 FROM civicrm_action_schedule cas
320 LEFT JOIN civicrm_action_mapping cam ON (cam.id = cas.mapping_id)
322 $params = CRM_Core_DAO
::$_nullArray;
324 if ($entityValue and $id) {
326 WHERE cas.entity_value = $id AND
327 cam.entity_value = '$entityValue'";
331 $params = array(1 => array($id, 'Integer'),
332 2 => array($entityValue, 'String'),
336 $dao = CRM_Core_DAO
::executeQuery($query);
337 while ($dao->fetch()) {
338 $list[$dao->id
]['id'] = $dao->id
;
339 $list[$dao->id
]['title'] = $dao->title
;
340 $list[$dao->id
]['start_action_offset'] = $dao->start_action_offset
;
341 $list[$dao->id
]['start_action_unit'] = $dao->start_action_unit
;
342 $list[$dao->id
]['start_action_condition'] = $dao->start_action_condition
;
343 $list[$dao->id
]['entityDate'] = ucwords(str_replace('_', ' ', $dao->entityDate
));
344 $list[$dao->id
]['absolute_date'] = $dao->absolute_date
;
346 $status = $dao->entityStatus
;
347 $statusArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityStatusIds
);
348 foreach ($statusArray as & $s) {
349 $s = CRM_Utils_Array
::value($s, $
$status);
351 $statusIds = implode(', ', $statusArray);
353 $value = $dao->entityValue
;
354 $valueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityValueIds
);
355 foreach ($valueArray as & $v) {
356 $v = CRM_Utils_Array
::value($v, $
$value);
358 $valueIds = implode(', ', $valueArray);
359 $list[$dao->id
]['entity'] = $entity[$dao->entity
];
360 $list[$dao->id
]['value'] = $valueIds;
361 $list[$dao->id
]['status'] = $statusIds;
362 $list[$dao->id
]['is_repeat'] = $dao->is_repeat
;
363 $list[$dao->id
]['is_active'] = $dao->is_active
;
369 static function sendReminder($contactId, $email, $scheduleID, $from, $tokenParams) {
371 $schedule = new CRM_Core_DAO_ActionSchedule();
372 $schedule->id
= $scheduleID;
374 $domain = CRM_Core_BAO_Domain
::getDomain();
376 $hookTokens = array();
378 if ($schedule->find(TRUE)) {
379 $body_text = $schedule->body_text
;
380 $body_html = $schedule->body_html
;
381 $body_subject = $schedule->subject
;
383 $body_text = CRM_Utils_String
::htmlToText($body_html);
386 $params = array(array('contact_id', '=', $contactId, 0, 0));
387 list($contact, $_) = CRM_Contact_BAO_Query
::apiQuery($params);
390 $contact = reset($contact);
392 if (!$contact ||
is_a($contact, 'CRM_Core_Error')) {
396 // merge activity tokens with contact array
397 $contact = array_merge($contact, $tokenParams);
400 CRM_Utils_Hook
::tokenValues($contact, $contactId);
402 CRM_Utils_Hook
::tokens($hookTokens);
403 $categories = array_keys($hookTokens);
405 $type = array('html', 'text');
407 foreach ($type as $key => $value) {
408 $dummy_mail = new CRM_Mailing_BAO_Mailing();
409 $bodyType = "body_{$value}";
410 $dummy_mail->$bodyType = $
$bodyType;
411 $tokens = $dummy_mail->getTokens();
414 CRM_Utils_Token
::replaceGreetingTokens($
$bodyType, NULL, $contact['contact_id']);
415 $
$bodyType = CRM_Utils_Token
::replaceDomainTokens($
$bodyType, $domain, TRUE, $tokens[$value], TRUE);
416 $
$bodyType = CRM_Utils_Token
::replaceContactTokens($
$bodyType, $contact, FALSE, $tokens[$value], FALSE, TRUE);
417 $
$bodyType = CRM_Utils_Token
::replaceComponentTokens($
$bodyType, $contact, $tokens[$value], TRUE, FALSE);
418 $
$bodyType = CRM_Utils_Token
::replaceHookTokens($
$bodyType, $contact, $categories, TRUE);
424 $smarty = CRM_Core_Smarty
::singleton();
426 'text', 'html') as $elem) {
427 $
$elem = $smarty->fetch("string:{$$elem}");
431 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
437 $subjectToken = NULL;
439 foreach ($matches[1] as $token) {
440 list($type, $name) = preg_split('/\./', $token, 2);
442 if (!isset($subjectToken['contact'])) {
443 $subjectToken['contact'] = array();
445 $subjectToken['contact'][] = $name;
450 $messageSubject = CRM_Utils_Token
::replaceContactTokens($body_subject, $contact, FALSE, $subjectToken);
451 $messageSubject = CRM_Utils_Token
::replaceDomainTokens($messageSubject, $domain, TRUE, $tokens[$value]);
452 $messageSubject = CRM_Utils_Token
::replaceComponentTokens($messageSubject, $contact, $tokens[$value], TRUE);
453 $messageSubject = CRM_Utils_Token
::replaceHookTokens($messageSubject, $contact, $categories, TRUE);
455 $messageSubject = $smarty->fetch("string:{$messageSubject}");
457 // set up the parameters for CRM_Utils_Mail::send
459 'groupName' => 'Scheduled Reminder Sender',
461 'toName' => $contact['display_name'],
463 'subject' => $messageSubject,
466 if (!$html ||
$contact['preferred_mail_format'] == 'Text' ||
467 $contact['preferred_mail_format'] == 'Both'
469 // render the & entities in text mode, so that the links work
470 $mailParams['text'] = str_replace('&', '&', $text);
472 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
473 $contact['preferred_mail_format'] == 'Both'
475 $mailParams['html'] = $html;
478 $result = CRM_Utils_Mail
::send($mailParams);
486 * Function to add the schedules reminders in the db
488 * @param array $params (reference ) an assoc array of name/value pairs
489 * @param array $ids the array that holds all the db ids
491 * @return object CRM_Core_DAO_ActionSchedule
496 static function add(&$params, &$ids) {
497 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
498 $actionSchedule->copyValues($params);
500 return $actionSchedule->save();
504 * Takes a bunch of params that are needed to match certain criteria and
505 * retrieves the relevant objects. It also stores all the retrieved
506 * values in the default array
508 * @param array $params (reference ) an assoc array of name/value pairs
509 * @param array $values (reference ) an assoc array to hold the flattened values
511 * @return object CRM_Core_DAO_ActionSchedule object on success, null otherwise
515 static function retrieve(&$params, &$values) {
516 if (empty($params)) {
519 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
521 $actionSchedule->copyValues($params);
523 if ($actionSchedule->find(TRUE)) {
524 $ids['actionSchedule'] = $actionSchedule->id
;
526 CRM_Core_DAO
::storeValues($actionSchedule, $values);
528 return $actionSchedule;
534 * Function to delete a Reminder
536 * @param int $id ID of the Reminder to be deleted.
541 static function del($id) {
543 $dao = new CRM_Core_DAO_ActionSchedule();
545 if ($dao->find(TRUE)) {
550 CRM_Core_Error
::fatal(ts('Invalid value passed to delete function.'));
554 * update the is_active flag in the db
556 * @param int $id id of the database record
557 * @param boolean $is_active value we want to set the is_active field
559 * @return Object DAO object on success, null otherwise
562 static function setIsActive($id, $is_active) {
563 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
566 static function sendMailings($mappingID, $now) {
567 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
568 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
570 $mapping = new CRM_Core_DAO_ActionMapping();
571 $mapping->id
= $mappingID;
572 $mapping->find(TRUE);
574 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
575 $actionSchedule->mapping_id
= $mappingID;
576 $actionSchedule->is_active
= 1;
577 $actionSchedule->find(FALSE);
579 $tokenFields = array();
580 $session = CRM_Core_Session
::singleton();
582 while ($actionSchedule->fetch()) {
583 $extraSelect = $extraJoin = $extraWhere = '';
585 if ($actionSchedule->record_activity
) {
586 if ($mapping->entity
== 'civicrm_membership') {
588 CRM_Core_OptionGroup
::getValue('activity_type', 'Membership Renewal Reminder', 'name');
592 CRM_Core_OptionGroup
::getValue('activity_type', 'Reminder Sent', 'name');
596 CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
599 if ($mapping->entity
== 'civicrm_activity') {
600 $tokenEntity = 'activity';
601 $tokenFields = array('activity_id', 'activity_type', 'subject', 'details', 'activity_date_time');
602 $extraSelect = ', ov.label as activity_type, e.id as activity_id';
603 $extraJoin = "INNER JOIN civicrm_option_group og ON og.name = 'activity_type'
604 INNER JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
605 $extraWhere = 'AND e.is_current_revision = 1 AND e.is_deleted = 0';
608 if ($mapping->entity
== 'civicrm_participant') {
609 $tokenEntity = 'event';
610 $tokenFields = array('event_type', 'title', 'event_id', 'start_date', 'end_date', 'summary', 'description', 'location', 'info_url', 'registration_url', 'fee_amount', 'contact_email', 'contact_phone');
611 $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 ';
614 INNER JOIN civicrm_event ev ON e.event_id = ev.id
615 INNER JOIN civicrm_option_group og ON og.name = 'event_type'
616 INNER JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
617 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
618 LEFT JOIN civicrm_address address ON address.id = lb.address_id
619 LEFT JOIN civicrm_email email ON email.id = lb.email_id
620 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
624 if ($mapping->entity
== 'civicrm_membership') {
625 $tokenEntity = 'membership';
626 $tokenFields = array('fee', 'id', 'join_date', 'start_date', 'end_date', 'status', 'type');
627 $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';
629 INNER JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
630 INNER JOIN civicrm_membership_status ms ON e.status_id = ms.id';
634 SELECT reminder.id as reminderID, reminder.*, e.id as entityID, e.* {$extraSelect}
635 FROM civicrm_action_log reminder
636 INNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id
638 WHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL
641 $dao = CRM_Core_DAO
::executeQuery($query,
642 array(1 => array($actionSchedule->id
, 'Integer'))
645 while ($dao->fetch()) {
646 $entityTokenParams = array();
647 foreach ($tokenFields as $field) {
648 if ($field == 'location') {
650 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
651 $loc['street_address'] = $dao->street_address
;
652 $loc['city'] = $dao->city
;
653 $loc['state_province'] = CRM_Utils_array
::value($dao->state_province_id
, $stateProvince);
654 $loc['postal_code'] = $dao->postal_code
;
655 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address
::format($loc);
657 elseif ($field == 'info_url') {
658 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
660 elseif ($field == 'registration_url') {
661 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
663 elseif (in_array($field, array('start_date','end_date','join_date','activity_date_time'))) {
664 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date
::customFormat($dao->$field);
667 $entityTokenParams["{$tokenEntity}." . $field] = $dao->$field;
673 $toEmail = CRM_Contact_BAO_Contact
::getPrimaryEmail($dao->contact_id
);
676 CRM_Core_BAO_ActionSchedule
::sendReminder(
684 if (!$result ||
is_a($result, 'PEAR_Error')) {
685 // we could not send an email, for now we ignore, CRM-3406
691 $errorMsg = "Couldn\'t find recipient\'s email address.";
694 // update action log record
696 'id' => $dao->reminderID
,
697 'is_error' => $isError,
698 'message' => $errorMsg ?
$errorMsg : "null",
699 'action_date_time' => $now,
701 CRM_Core_BAO_ActionLog
::create($logParams);
703 // insert activity log record if needed
704 if ($actionSchedule->record_activity
) {
705 $activityParams = array(
706 'subject' => $actionSchedule->title
,
707 'details' => $actionSchedule->body_html
,
708 'source_contact_id' =>
709 $session->get('userID') ?
$session->get('userID') : $dao->contact_id
,
710 'target_contact_id' => $dao->contact_id
,
711 'activity_date_time' => date('YmdHis'),
712 'status_id' => $activityStatusID,
713 'activity_type_id' => $activityTypeID,
714 'source_record_id' => $dao->entityID
,
716 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
724 static function buildRecipientContacts($mappingID, $now) {
725 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
726 $actionSchedule->mapping_id
= $mappingID;
727 $actionSchedule->is_active
= 1;
728 $actionSchedule->find();
730 while ($actionSchedule->fetch()) {
731 $mapping = new CRM_Core_DAO_ActionMapping();
732 $mapping->id
= $mappingID;
733 $mapping->find(TRUE);
735 $select = $join = $where = array();
737 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
738 trim($actionSchedule->entity_value
, CRM_Core_DAO
::VALUE_SEPARATOR
)
740 $value = implode(',', $value);
742 $status = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
743 trim($actionSchedule->entity_status
, CRM_Core_DAO
::VALUE_SEPARATOR
)
745 $status = implode(',', $status);
747 if (!CRM_Utils_System
::isNull($mapping->entity_recipient
)) {
748 $recipientOptions = CRM_Core_OptionGroup
::values($mapping->entity_recipient
);
750 $from = "{$mapping->entity} e";
752 if ($mapping->entity
== 'civicrm_activity') {
753 $contactField = 'r.contact_id';
754 $activityContacts = CRM_Core_PseudoConstant
::activityContacts('name');
755 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
756 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
757 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
759 switch (CRM_Utils_Array
::value($actionSchedule->recipient
, $recipientOptions)) {
760 case 'Activity Assignees':
761 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$assigneeID}";
764 case 'Activity Source':
765 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$sourceID}";
769 case 'Activity Targets':
770 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
774 // build where clause
775 if (!empty($value)) {
776 $where[] = "e.activity_type_id IN ({$value})";
779 $where[] = "e.activity_type_id IS NULL";
781 if (!empty($status)) {
782 $where[] = "e.status_id IN ({$status})";
784 $where[] = ' e.is_current_revision = 1 ';
785 $where[] = ' e.is_deleted = 0 ';
787 $dateField = 'e.activity_date_time';
790 if ($mapping->entity
== 'civicrm_participant') {
791 $contactField = 'e.contact_id';
792 $join[] = 'INNER JOIN civicrm_event r ON e.event_id = r.id';
793 if ($actionSchedule->recipient_listing
) {
794 $rList = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
795 trim($actionSchedule->recipient_listing
, CRM_Core_DAO
::VALUE_SEPARATOR
)
797 $rList = implode(',', $rList);
799 switch ($recipientOptions[$actionSchedule->recipient
]) {
800 case 'Participant Role':
801 $where[] = "e.role_id IN ({$rList})";
809 // build where clause
810 if (!empty($value)) {
811 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IN ({$value})" : "r.id IN ({$value})";
814 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IS NULL" : "r.id IS NULL";
817 if (!empty($status)) {
818 $where[] = "e.status_id IN ({$status})";
821 $where[] = 'r.is_active = 1';
822 $where[] = 'r.is_template = 0';
823 $dateField = str_replace('event_', 'r.', $actionSchedule->start_action_date
);
827 if ($mapping->entity
== 'civicrm_membership') {
828 $contactField = 'e.contact_id';
830 // build where clause
831 if ( $status == 2 ) {
832 //auto-renew memberships
833 $where[] = "e.contribution_recur_id IS NOT NULL ";
835 elseif ( $status == 1 ) {
836 $where[] = "e.contribution_recur_id IS NULL ";
839 // build where clause
840 if (!empty($value)) {
841 $where[] = "e.membership_type_id IN ({$value})";
844 $where[] = "e.membership_type_id IS NULL";
847 $where[] = "( e.is_override IS NULL OR e.is_override = 0 )";
848 $dateField = str_replace('membership_', 'e.', $actionSchedule->start_action_date
);
849 $notINClause = self
::permissionedRelationships($contactField);
851 $membershipStatus = CRM_Member_PseudoConstant
::membershipStatus(NULL, "is_current_member = 1 OR name = 'Expired'", 'id');
852 $mStatus = implode (',', $membershipStatus);
853 $where[] = "e.status_id IN ({$mStatus})";
857 if ($actionSchedule->group_id
) {
858 $join[] = "INNER JOIN civicrm_group_contact grp ON {$contactField} = grp.contact_id AND grp.status = 'Added'";
859 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
861 elseif (!empty($actionSchedule->recipient_manual
)) {
862 $rList = CRM_Utils_Type
::escape($actionSchedule->recipient_manual
, 'String');
863 $where[] = "{$contactField} IN ({$rList})";
866 $select[] = "{$contactField} as contact_id";
867 $select[] = 'e.id as entity_id';
868 $select[] = "'{$mapping->entity}' as entity_table";
869 $select[] = "{$actionSchedule->id} as action_schedule_id";
870 $reminderJoinClause = "civicrm_action_log reminder ON reminder.contact_id = {$contactField} AND
871 reminder.entity_id = e.id AND
872 reminder.entity_table = '{$mapping->entity}' AND
873 reminder.action_schedule_id = %1";
875 $join[] = "INNER JOIN civicrm_contact c ON c.id = {$contactField} AND c.is_deleted = 0 AND c.is_deceased = 0 ";
877 if ($actionSchedule->start_action_date
) {
878 $startDateClause = array();
879 $op = ($actionSchedule->start_action_condition
== 'before' ?
'<=' : '>=');
880 $operator = ($actionSchedule->start_action_condition
== 'before' ?
'DATE_SUB' : 'DATE_ADD');
881 $date = $operator . "({$dateField}, INTERVAL {$actionSchedule->start_action_offset} {$actionSchedule->start_action_unit})";
882 $startDateClause[] = "'{$now}' >= {$date}";
883 if ($mapping->entity
== 'civicrm_participant') {
884 $startDateClause[] = $operator. "({$now}, INTERVAL 1 DAY ) {$op} " . $dateField;
887 $startDateClause[] = "DATE_SUB({$now}, INTERVAL 1 DAY ) <= {$date}";
890 $startDate = implode(' AND ', $startDateClause);
892 elseif ($actionSchedule->absolute_date
) {
893 $startDate = "DATEDIFF(DATE('{$now}'),'{$actionSchedule->absolute_date}') = 0";
896 // ( now >= date_built_from_start_time ) OR ( now = absolute_date )
897 $dateClause = "reminder.id IS NULL AND {$startDate}";
899 // start composing query
900 $selectClause = 'SELECT ' . implode(', ', $select);
901 $fromClause = "FROM $from";
902 $joinClause = !empty($join) ?
implode(' ', $join) : '';
903 $whereClause = 'WHERE ' . implode(' AND ', $where);
906 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
910 LEFT JOIN {$reminderJoinClause}
911 {$whereClause} AND {$dateClause} {$notINClause}";
913 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
915 // if repeat is turned ON:
916 if ($actionSchedule->is_repeat
) {
917 $repeatEvent = ($actionSchedule->end_action
== 'before' ?
'DATE_SUB' : 'DATE_ADD') . "({$dateField}, INTERVAL {$actionSchedule->end_frequency_interval} {$actionSchedule->end_frequency_unit})";
919 if ($actionSchedule->repetition_frequency_unit
== 'day') {
920 $hrs = 24 * $actionSchedule->repetition_frequency_interval
;
922 elseif ($actionSchedule->repetition_frequency_unit
== 'week') {
923 $hrs = 24 * $actionSchedule->repetition_frequency_interval
* 7;
926 $hrs = $actionSchedule->repetition_frequency_interval
;
929 // (now <= repeat_end_time )
930 $repeatEventClause = "'{$now}' <= {$repeatEvent}";
931 // diff(now && logged_date_time) >= repeat_interval
932 $havingClause = "HAVING TIMEDIFF({$now}, latest_log_time) >= TIME('{$hrs}:00:00')";
933 $groupByClause = 'GROUP BY reminder.contact_id, reminder.entity_id, reminder.entity_table';
934 $selectClause .= ', MAX(reminder.action_date_time) as latest_log_time';
936 $sqlInsertValues = "{$selectClause}
939 INNER JOIN {$reminderJoinClause}
940 {$whereClause} AND {$repeatEventClause}
944 $valsqlInsertValues = CRM_Core_DAO
::executeQuery($sqlInsertValues, array(1 => array($actionSchedule->id
, 'Integer')));
946 $arrValues = array();
947 while ($valsqlInsertValues->fetch()) {
948 $arrValues[] = "( {$valsqlInsertValues->contact_id}, {$valsqlInsertValues->entity_id}, '{$valsqlInsertValues->entity_table}',{$valsqlInsertValues->action_schedule_id} )";
951 $valString = implode(',', $arrValues);
955 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
956 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
962 static function permissionedRelationships($field) {
964 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
965 FROM civicrm_membership m
966 LEFT JOIN civicrm_membership cm ON cm.id = m.owner_membership_id
967 LEFT JOIN civicrm_membership_type cmt ON cmt.id = m.membership_type_id
968 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 )
969 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 ) )
970 WHERE m.owner_membership_id IS NOT NULL AND
971 ( rel.is_permission_a_b = 0 OR rel.is_permission_b_a = 0)
974 $excludeIds = array();
975 $dao = CRM_Core_DAO
::executeQuery($query, array());
976 while ($dao->fetch()) {
977 if ($dao->slave_contact
== $dao->contact_id_a
&& $dao->is_permission_b_a
== 0) {
978 $excludeIds[] = $dao->slave_contact
;
980 elseif ($dao->slave_contact
== $dao->contact_id_b
&& $dao->is_permission_a_b
== 0) {
981 $excludeIds[] = $dao->slave_contact
;
985 if (!empty($excludeIds)) {
986 $clause = "AND {$field} NOT IN ( " .implode(', ', $excludeIds) . ' ) ';
992 static function processQueue($now = NULL) {
993 $now = $now ? CRM_Utils_Time
::setTime($now) : CRM_Utils_Time
::getTime();
995 $mappings = self
::getMapping();
996 foreach ($mappings as $mappingID => $mapping) {
997 self
::buildRecipientContacts($mappingID, $now);
998 self
::sendMailings($mappingID, $now);
1003 'messages' => ts('Sent all scheduled reminders successfully'),
1008 static function isConfigured($id, $mappingID) {
1009 $queryString = "SELECT count(id) FROM civicrm_action_schedule
1010 WHERE mapping_id = %1 AND
1013 $params = array(1 => array($mappingID, 'Integer'),
1014 2 => array($id, 'Integer'),
1016 return CRM_Core_DAO
::singleValueQuery($queryString, $params);
1019 static function getRecipientListing($mappingID, $recipientType) {
1021 if (!$mappingID ||
!$recipientType) {
1025 $mapping = self
::getMapping($mappingID);
1027 switch ($mapping['entity']) {
1028 case 'civicrm_participant':
1029 $eventContacts = CRM_Core_PseudoConstant
::eventContacts('name');
1030 if (!CRM_Utils_Array
::value($recipientType, $eventContacts)) {
1033 if ($eventContacts[$recipientType] == 'Participant Role') {
1034 $options = CRM_Event_PseudoConstant
::participantRole();