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(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_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, $email, $scheduleID, $from, $tokenParams) {
373 $schedule = new CRM_Core_DAO_ActionSchedule();
374 $schedule->id
= $scheduleID;
376 $domain = CRM_Core_BAO_Domain
::getDomain();
378 $hookTokens = array();
380 if ($schedule->find(TRUE)) {
381 $body_text = $schedule->body_text
;
382 $body_html = $schedule->body_html
;
383 $body_subject = $schedule->subject
;
385 $body_text = CRM_Utils_String
::htmlToText($body_html);
388 $params = array(array('contact_id', '=', $contactId, 0, 0));
389 list($contact, $_) = CRM_Contact_BAO_Query
::apiQuery($params);
392 $contact = reset($contact);
394 if (!$contact ||
is_a($contact, 'CRM_Core_Error')) {
398 // merge activity tokens with contact array
399 $contact = array_merge($contact, $tokenParams);
402 CRM_Utils_Hook
::tokenValues($contact, $contactId);
404 CRM_Utils_Hook
::tokens($hookTokens);
405 $categories = array_keys($hookTokens);
407 $type = array('html', 'text');
409 foreach ($type as $key => $value) {
410 $dummy_mail = new CRM_Mailing_BAO_Mailing();
411 $bodyType = "body_{$value}";
412 $dummy_mail->$bodyType = $
$bodyType;
413 $tokens = $dummy_mail->getTokens();
416 CRM_Utils_Token
::replaceGreetingTokens($
$bodyType, NULL, $contact['contact_id']);
417 $
$bodyType = CRM_Utils_Token
::replaceDomainTokens($
$bodyType, $domain, TRUE, $tokens[$value], TRUE);
418 $
$bodyType = CRM_Utils_Token
::replaceContactTokens($
$bodyType, $contact, FALSE, $tokens[$value], FALSE, TRUE);
419 $
$bodyType = CRM_Utils_Token
::replaceComponentTokens($
$bodyType, $contact, $tokens[$value], TRUE, FALSE);
420 $
$bodyType = CRM_Utils_Token
::replaceHookTokens($
$bodyType, $contact, $categories, TRUE);
426 $smarty = CRM_Core_Smarty
::singleton();
428 'text', 'html') as $elem) {
429 $
$elem = $smarty->fetch("string:{$$elem}");
433 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
439 $subjectToken = NULL;
441 foreach ($matches[1] as $token) {
442 list($type, $name) = preg_split('/\./', $token, 2);
444 if (!isset($subjectToken['contact'])) {
445 $subjectToken['contact'] = array();
447 $subjectToken['contact'][] = $name;
452 $messageSubject = CRM_Utils_Token
::replaceContactTokens($body_subject, $contact, FALSE, $subjectToken);
453 $messageSubject = CRM_Utils_Token
::replaceDomainTokens($messageSubject, $domain, TRUE, $tokens[$value]);
454 $messageSubject = CRM_Utils_Token
::replaceComponentTokens($messageSubject, $contact, $tokens[$value], TRUE);
455 $messageSubject = CRM_Utils_Token
::replaceHookTokens($messageSubject, $contact, $categories, TRUE);
457 $messageSubject = $smarty->fetch("string:{$messageSubject}");
459 // set up the parameters for CRM_Utils_Mail::send
461 'groupName' => 'Scheduled Reminder Sender',
463 'toName' => $contact['display_name'],
465 'subject' => $messageSubject,
468 if (!$html ||
$contact['preferred_mail_format'] == 'Text' ||
469 $contact['preferred_mail_format'] == 'Both'
471 // render the & entities in text mode, so that the links work
472 $mailParams['text'] = str_replace('&', '&', $text);
474 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
475 $contact['preferred_mail_format'] == 'Both'
477 $mailParams['html'] = $html;
480 $result = CRM_Utils_Mail
::send($mailParams);
488 * Function to add the schedules reminders in the db
490 * @param array $params (reference ) an assoc array of name/value pairs
491 * @param array $ids the array that holds all the db ids
493 * @return object CRM_Core_DAO_ActionSchedule
498 static function add(&$params, &$ids = NULL) {
499 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
500 $actionSchedule->copyValues($params);
502 return $actionSchedule->save();
506 * Takes a bunch of params that are needed to match certain criteria and
507 * retrieves the relevant objects. It also stores all the retrieved
508 * values in the default array
510 * @param array $params (reference ) an assoc array of name/value pairs
511 * @param array $values (reference ) an assoc array to hold the flattened values
513 * @return object CRM_Core_DAO_ActionSchedule object on success, null otherwise
517 static function retrieve(&$params, &$values) {
518 if (empty($params)) {
521 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
523 $actionSchedule->copyValues($params);
525 if ($actionSchedule->find(TRUE)) {
526 $ids['actionSchedule'] = $actionSchedule->id
;
528 CRM_Core_DAO
::storeValues($actionSchedule, $values);
530 return $actionSchedule;
536 * Function to delete a Reminder
538 * @param int $id ID of the Reminder to be deleted.
543 static function del($id) {
545 $dao = new CRM_Core_DAO_ActionSchedule();
547 if ($dao->find(TRUE)) {
552 CRM_Core_Error
::fatal(ts('Invalid value passed to delete function.'));
556 * update the is_active flag in the db
558 * @param int $id id of the database record
559 * @param boolean $is_active value we want to set the is_active field
561 * @return Object DAO object on success, null otherwise
564 static function setIsActive($id, $is_active) {
565 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
568 static function sendMailings($mappingID, $now) {
569 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
570 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
572 $mapping = new CRM_Core_DAO_ActionMapping();
573 $mapping->id
= $mappingID;
574 $mapping->find(TRUE);
576 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
577 $actionSchedule->mapping_id
= $mappingID;
578 $actionSchedule->is_active
= 1;
579 $actionSchedule->find(FALSE);
581 $tokenFields = array();
582 $session = CRM_Core_Session
::singleton();
584 while ($actionSchedule->fetch()) {
585 $extraSelect = $extraJoin = $extraWhere = $extraOn = '';
587 if ($actionSchedule->record_activity
) {
588 if ($mapping->entity
== 'civicrm_membership') {
590 CRM_Core_OptionGroup
::getValue('activity_type', 'Membership Renewal Reminder', 'name');
594 CRM_Core_OptionGroup
::getValue('activity_type', 'Reminder Sent', 'name');
598 CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
601 if ($mapping->entity
== 'civicrm_activity') {
602 $tokenEntity = 'activity';
603 $tokenFields = array('activity_id', 'activity_type', 'subject', 'details', 'activity_date_time');
604 $extraSelect = ', ov.label as activity_type, e.id as activity_id';
606 INNER JOIN civicrm_option_group og ON og.name = 'activity_type'
607 INNER JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
608 $extraOn = ' AND e.is_current_revision = 1 AND e.is_deleted = 0 ';
609 if ($actionSchedule->limit_to
== 0) {
611 LEFT JOIN civicrm_option_group og ON og.name = 'activity_type'
612 LEFT JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
616 if ($mapping->entity
== 'civicrm_participant') {
617 $tokenEntity = 'event';
618 $tokenFields = array('event_type', 'title', 'event_id', 'start_date', 'end_date', 'summary', 'description', 'location', 'info_url', 'registration_url', 'fee_amount', 'contact_email', 'contact_phone');
619 $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 ';
622 INNER JOIN civicrm_event ev ON e.event_id = ev.id
623 INNER JOIN civicrm_option_group og ON og.name = 'event_type'
624 INNER JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
625 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
626 LEFT JOIN civicrm_address address ON address.id = lb.address_id
627 LEFT JOIN civicrm_email email ON email.id = lb.email_id
628 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
630 if ($actionSchedule->limit_to
== 0) {
632 LEFT JOIN civicrm_event ev ON e.event_id = ev.id
633 LEFT JOIN civicrm_option_group og ON og.name = 'event_type'
634 LEFT JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
635 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
636 LEFT JOIN civicrm_address address ON address.id = lb.address_id
637 LEFT JOIN civicrm_email email ON email.id = lb.email_id
638 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
643 if ($mapping->entity
== 'civicrm_membership') {
644 $tokenEntity = 'membership';
645 $tokenFields = array('fee', 'id', 'join_date', 'start_date', 'end_date', 'status', 'type');
646 $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';
648 INNER JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
649 INNER JOIN civicrm_membership_status ms ON e.status_id = ms.id';
651 if ($actionSchedule->limit_to
== 0) {
653 LEFT JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
654 LEFT JOIN civicrm_membership_status ms ON e.status_id = ms.id';
658 $entityJoinClause = "INNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
659 if ($actionSchedule->limit_to
== 0) {
660 $entityJoinClause = "LEFT JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
661 $extraWhere .= " AND (e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact')";
663 $entityJoinClause .= $extraOn;
666 SELECT reminder.id as reminderID, reminder.contact_id as contactID, reminder.*, e.id as entityID, e.* {$extraSelect}
667 FROM civicrm_action_log reminder
670 WHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL
673 $dao = CRM_Core_DAO
::executeQuery($query,
674 array(1 => array($actionSchedule->id
, 'Integer'))
677 while ($dao->fetch()) {
678 $entityTokenParams = array();
679 foreach ($tokenFields as $field) {
680 if ($field == 'location') {
682 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
683 $loc['street_address'] = $dao->street_address
;
684 $loc['city'] = $dao->city
;
685 $loc['state_province'] = CRM_Utils_array
::value($dao->state_province_id
, $stateProvince);
686 $loc['postal_code'] = $dao->postal_code
;
687 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address
::format($loc);
689 elseif ($field == 'info_url') {
690 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
692 elseif ($field == 'registration_url') {
693 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System
::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id
, TRUE, NULL, FALSE);
695 elseif (in_array($field, array('start_date','end_date','join_date','activity_date_time'))) {
696 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date
::customFormat($dao->$field);
699 $entityTokenParams["{$tokenEntity}." . $field] = $dao->$field;
705 $toEmail = CRM_Contact_BAO_Contact
::getPrimaryEmail($dao->contactID
);
708 CRM_Core_BAO_ActionSchedule
::sendReminder(
716 if (!$result ||
is_a($result, 'PEAR_Error')) {
717 // we could not send an email, for now we ignore, CRM-3406
723 $errorMsg = "Couldn\'t find recipient\'s email address.";
726 // update action log record
728 'id' => $dao->reminderID
,
729 'is_error' => $isError,
730 'message' => $errorMsg ?
$errorMsg : "null",
731 'action_date_time' => $now,
733 CRM_Core_BAO_ActionLog
::create($logParams);
735 // insert activity log record if needed
736 if ($actionSchedule->record_activity
) {
737 $activityParams = array(
738 'subject' => $actionSchedule->title
,
739 'details' => $actionSchedule->body_html
,
740 'source_contact_id' =>
741 $session->get('userID') ?
$session->get('userID') : $dao->contactID
,
742 'target_contact_id' => $dao->contactID
,
743 'activity_date_time' => date('YmdHis'),
744 'status_id' => $activityStatusID,
745 'activity_type_id' => $activityTypeID,
746 'source_record_id' => $dao->entityID
,
748 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
756 static function buildRecipientContacts($mappingID, $now) {
757 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
758 $actionSchedule->mapping_id
= $mappingID;
759 $actionSchedule->is_active
= 1;
760 $actionSchedule->find();
762 while ($actionSchedule->fetch()) {
763 $mapping = new CRM_Core_DAO_ActionMapping();
764 $mapping->id
= $mappingID;
765 $mapping->find(TRUE);
767 // note: $where - this filtering applies for both
768 // 'limit to' and 'addition to' options
769 // $limitWhere - this filtering applies only for
771 $select = $join = $where = $limitWhere = array();
772 $limitTo = $actionSchedule->limit_to
;
773 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
774 trim($actionSchedule->entity_value
, CRM_Core_DAO
::VALUE_SEPARATOR
)
776 $value = implode(',', $value);
778 $status = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
779 trim($actionSchedule->entity_status
, CRM_Core_DAO
::VALUE_SEPARATOR
)
781 $status = implode(',', $status);
783 if (!CRM_Utils_System
::isNull($mapping->entity_recipient
)) {
784 $recipientOptions = CRM_Core_OptionGroup
::values($mapping->entity_recipient
, FALSE, FALSE, FALSE, NULL, 'name');
786 $from = "{$mapping->entity} e";
788 if ($mapping->entity
== 'civicrm_activity') {
789 $contactField = 'r.contact_id';
790 $table = 'civicrm_activity e';
791 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
792 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
793 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
794 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
797 // including the activity target contacts if 'in addition' is defined
798 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
801 switch (CRM_Utils_Array
::value($actionSchedule->recipient
, $recipientOptions)) {
802 case 'Activity Assignees':
803 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$assigneeID}";
806 case 'Activity Source':
807 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$sourceID}";
811 case 'Activity Targets':
812 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
816 // build where clause
817 if (!empty($value)) {
818 $where[] = "e.activity_type_id IN ({$value})";
821 $where[] = "e.activity_type_id IS NULL";
823 if (!empty($status)) {
824 $where[] = "e.status_id IN ({$status})";
826 $where[] = ' e.is_current_revision = 1 ';
827 $where[] = ' e.is_deleted = 0 ';
829 $dateField = 'e.activity_date_time';
832 if ($mapping->entity
== 'civicrm_participant') {
833 $table = 'civicrm_event r';
834 $contactField = 'e.contact_id';
835 $join[] = 'INNER JOIN civicrm_event r ON e.event_id = r.id';
836 if ($actionSchedule->recipient_listing
&& $limitTo) {
837 $rList = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
838 trim($actionSchedule->recipient_listing
, CRM_Core_DAO
::VALUE_SEPARATOR
)
840 $rList = implode(',', $rList);
842 switch ($recipientOptions[$actionSchedule->recipient
]) {
843 case 'participant_role':
844 $where[] = "e.role_id IN ({$rList})";
852 // build where clause
853 if (!empty($value)) {
854 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IN ({$value})" : "r.id IN ({$value})";
857 $where[] = ($mapping->entity_value
== 'event_type') ?
"r.event_type_id IS NULL" : "r.id IS NULL";
860 // participant status criteria not to be implemented
861 // for additional recipients
862 if (!empty($status)) {
863 $limitWhere[] = "e.status_id IN ({$status})";
866 $where[] = 'r.is_active = 1';
867 $where[] = 'r.is_template = 0';
868 $dateField = str_replace('event_', 'r.', $actionSchedule->start_action_date
);
872 if ($mapping->entity
== 'civicrm_membership') {
873 $contactField = 'e.contact_id';
874 $table = 'civicrm_membership e';
875 // build where clause
876 if ( $status == 2 ) {
877 //auto-renew memberships
878 $where[] = "e.contribution_recur_id IS NOT NULL ";
880 elseif ( $status == 1 ) {
881 $where[] = "e.contribution_recur_id IS NULL ";
884 // build where clause
885 if (!empty($value)) {
886 $where[] = "e.membership_type_id IN ({$value})";
889 $where[] = "e.membership_type_id IS NULL";
892 $where[] = "( e.is_override IS NULL OR e.is_override = 0 )";
893 $dateField = str_replace('membership_', 'e.', $actionSchedule->start_action_date
);
894 $notINClause = self
::permissionedRelationships($contactField);
896 $membershipStatus = CRM_Member_PseudoConstant
::membershipStatus(NULL, "(is_current_member = 1 OR name = 'Expired')", 'id');
897 $mStatus = implode (',', $membershipStatus);
898 $where[] = "e.status_id IN ({$mStatus})";
901 // CRM-13577 Introduce Smart Groups Handling
902 if ($actionSchedule->group_id
) {
904 // Need to check if its a smart group or not
905 // Then decide which table to join onto the query
906 $group = CRM_Contact_DAO_Group
::getTableName();
908 // Get the group information
910 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
912 WHERE $group.id = {$actionSchedule->group_id}
915 $groupDAO = CRM_Core_DAO
::executeQuery($sql);
916 $isSmartGroup = FALSE;
918 $groupDAO->fetch() &&
919 !empty($groupDAO->saved_search_id
)
921 // Check that the group is in place in the cache and up to date
922 CRM_Contact_BAO_GroupContactCache
::check($actionSchedule->group_id
);
923 // Set smart group flag
924 $isSmartGroup = TRUE;
927 // CRM-13577 End Introduce Smart Groups Handling
930 if ($actionSchedule->group_id
) {
931 // CRM-13577 If smart group then use Cache table
933 $join[] = "INNER JOIN civicrm_group_contact_cache grp ON {$contactField} = grp.contact_id";
934 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
936 $join[] = "INNER JOIN civicrm_group_contact grp ON {$contactField} = grp.contact_id AND grp.status = 'Added'";
937 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
940 elseif (!empty($actionSchedule->recipient_manual
)) {
941 $rList = CRM_Utils_Type
::escape($actionSchedule->recipient_manual
, 'String');
942 $where[] = "{$contactField} IN ({$rList})";
946 $addGroup = $addWhere = '';
947 if ($actionSchedule->group_id
) {
948 // CRM-13577 If smart group then use Cache table
950 $addGroup = " INNER JOIN civicrm_group_contact_cache grp ON c.id = grp.contact_id";
951 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
953 $addGroup = " INNER JOIN civicrm_group_contact grp ON c.id = grp.contact_id AND grp.status = 'Added'";
954 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
957 if (!empty($actionSchedule->recipient_manual
)) {
958 $rList = CRM_Utils_Type
::escape($actionSchedule->recipient_manual
, 'String');
959 $addWhere = "c.id IN ({$rList})";
963 $select[] = "{$contactField} as contact_id";
964 $select[] = 'e.id as entity_id';
965 $select[] = "'{$mapping->entity}' as entity_table";
966 $select[] = "{$actionSchedule->id} as action_schedule_id";
967 $reminderJoinClause = "civicrm_action_log reminder ON reminder.contact_id = {$contactField} AND
968 reminder.entity_id = e.id AND
969 reminder.entity_table = '{$mapping->entity}' AND
970 reminder.action_schedule_id = %1";
972 $join[] = "INNER JOIN civicrm_contact c ON c.id = {$contactField} AND c.is_deleted = 0 AND c.is_deceased = 0 ";
974 if ($actionSchedule->start_action_date
) {
975 $startDateClause = array();
976 $op = ($actionSchedule->start_action_condition
== 'before' ?
'<=' : '>=');
977 $operator = ($actionSchedule->start_action_condition
== 'before' ?
'DATE_SUB' : 'DATE_ADD');
978 $date = $operator . "({$dateField}, INTERVAL {$actionSchedule->start_action_offset} {$actionSchedule->start_action_unit})";
979 $startDateClause[] = "'{$now}' >= {$date}";
980 if ($mapping->entity
== 'civicrm_participant') {
981 $startDateClause[] = $operator. "({$now}, INTERVAL 1 DAY ) {$op} " . $dateField;
984 $startDateClause[] = "DATE_SUB({$now}, INTERVAL 1 DAY ) <= {$date}";
987 $startDate = implode(' AND ', $startDateClause);
989 elseif ($actionSchedule->absolute_date
) {
990 $startDate = "DATEDIFF(DATE('{$now}'),'{$actionSchedule->absolute_date}') = 0";
993 // ( now >= date_built_from_start_time ) OR ( now = absolute_date )
994 $dateClause = "reminder.id IS NULL AND {$startDate}";
996 // start composing query
997 $selectClause = 'SELECT ' . implode(', ', $select);
998 $fromClause = "FROM $from";
999 $joinClause = !empty($join) ?
implode(' ', $join) : '';
1000 $whereClause = 'WHERE ' . implode(' AND ', $where);
1001 $limitWhereClause = '';
1002 if (!empty($limitWhere)) {
1003 $limitWhereClause = ' AND ' . implode(' AND ', $limitWhere);
1007 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1011 LEFT JOIN {$reminderJoinClause}
1012 {$whereClause} {$limitWhereClause} AND {$dateClause} {$notINClause}
1014 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
1016 if ($limitTo == 0) {
1017 $additionWhere = ' WHERE ';
1018 if ($actionSchedule->start_action_date
) {
1019 $additionWhere = $whereClause . ' AND ';
1021 $contactTable = "civicrm_contact c";
1022 $addSelect = "SELECT c.id as contact_id, c.id as entity_id, 'civicrm_contact' as entity_table, {$actionSchedule->id} as action_schedule_id";
1023 $additionReminderClause = "civicrm_action_log reminder ON reminder.contact_id = c.id AND
1024 reminder.entity_id = c.id AND
1025 reminder.entity_table = 'civicrm_contact' AND
1026 reminder.action_schedule_id = {$actionSchedule->id}";
1028 $insertAdditionalSql ="
1029 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1031 FROM ({$contactTable}, {$table})
1032 LEFT JOIN {$additionReminderClause}
1034 {$additionWhere} c.is_deleted = 0 AND c.is_deceased = 0 AND {$addWhere}
1037 SELECT rem.contact_id
1038 FROM civicrm_action_log rem INNER JOIN {$mapping->entity} e ON rem.entity_id = e.id
1039 WHERE rem.action_schedule_id = {$actionSchedule->id}
1040 AND rem.entity_table = '{$mapping->entity}'
1044 CRM_Core_DAO
::executeQuery($insertAdditionalSql);
1046 // if repeat is turned ON:
1047 if ($actionSchedule->is_repeat
) {
1048 $repeatEvent = ($actionSchedule->end_action
== 'before' ?
'DATE_SUB' : 'DATE_ADD') . "({$dateField}, INTERVAL {$actionSchedule->end_frequency_interval} {$actionSchedule->end_frequency_unit})";
1050 if ($actionSchedule->repetition_frequency_unit
== 'day') {
1051 $hrs = 24 * $actionSchedule->repetition_frequency_interval
;
1053 elseif ($actionSchedule->repetition_frequency_unit
== 'week') {
1054 $hrs = 24 * $actionSchedule->repetition_frequency_interval
* 7;
1057 $hrs = $actionSchedule->repetition_frequency_interval
;
1060 // (now <= repeat_end_time )
1061 $repeatEventClause = "'{$now}' <= {$repeatEvent}";
1062 // diff(now && logged_date_time) >= repeat_interval
1063 $havingClause = "HAVING TIMEDIFF({$now}, latest_log_time) >= TIME('{$hrs}:00:00')";
1064 $groupByClause = 'GROUP BY reminder.contact_id, reminder.entity_id, reminder.entity_table';
1065 $selectClause .= ', MAX(reminder.action_date_time) as latest_log_time';
1066 $sqlInsertValues = "{$selectClause}
1069 INNER JOIN {$reminderJoinClause}
1070 {$whereClause} {$limitWhereClause} AND {$repeatEventClause}
1074 $valsqlInsertValues = CRM_Core_DAO
::executeQuery($sqlInsertValues, array(1 => array($actionSchedule->id
, 'Integer')));
1076 $arrValues = array();
1077 while ($valsqlInsertValues->fetch()) {
1078 $arrValues[] = "( {$valsqlInsertValues->contact_id}, {$valsqlInsertValues->entity_id}, '{$valsqlInsertValues->entity_table}',{$valsqlInsertValues->action_schedule_id} )";
1081 $valString = implode(',', $arrValues);
1085 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1086 CRM_Core_DAO
::executeQuery($query, array(1 => array($actionSchedule->id
, 'Integer')));
1089 if ($limitTo == 0) {
1090 $addSelect .= ', MAX(reminder.action_date_time) as latest_log_time';
1091 $sqlEndEventCheck = "
1092 SELECT * FROM {$table}
1093 {$whereClause} AND {$repeatEventClause} LIMIT 1";
1095 $daoCheck = CRM_Core_DAO
::executeQuery($sqlEndEventCheck);
1096 if ($daoCheck->fetch()) {
1097 $valSqlAdditionInsert = "
1099 FROM {$contactTable}
1101 INNER JOIN {$additionReminderClause}
1102 WHERE {$addWhere} AND c.is_deleted = 0 AND c.is_deceased = 0
1103 GROUP BY reminder.contact_id
1106 $daoForVals = CRM_Core_DAO
::executeQuery($valSqlAdditionInsert);
1107 $addValues = array();
1108 while ($daoForVals->fetch()) {
1109 $addValues[] = "( {$daoForVals->contact_id}, {$daoForVals->entity_id}, '{$daoForVals->entity_table}',{$daoForVals->action_schedule_id} )";
1111 $valString = implode(',', $addValues);
1115 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1116 CRM_Core_DAO
::executeQuery($query);
1124 static function permissionedRelationships($field) {
1126 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
1127 FROM civicrm_membership m
1128 LEFT JOIN civicrm_membership cm ON cm.id = m.owner_membership_id
1129 LEFT JOIN civicrm_membership_type cmt ON cmt.id = m.membership_type_id
1130 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 )
1131 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 ) )
1132 WHERE m.owner_membership_id IS NOT NULL AND
1133 ( rel.is_permission_a_b = 0 OR rel.is_permission_b_a = 0)
1136 $excludeIds = array();
1137 $dao = CRM_Core_DAO
::executeQuery($query, array());
1138 while ($dao->fetch()) {
1139 if ($dao->slave_contact
== $dao->contact_id_a
&& $dao->is_permission_b_a
== 0) {
1140 $excludeIds[] = $dao->slave_contact
;
1142 elseif ($dao->slave_contact
== $dao->contact_id_b
&& $dao->is_permission_a_b
== 0) {
1143 $excludeIds[] = $dao->slave_contact
;
1147 if (!empty($excludeIds)) {
1148 $clause = "AND {$field} NOT IN ( " .implode(', ', $excludeIds) . ' ) ';
1154 static function processQueue($now = NULL) {
1155 $now = $now ? CRM_Utils_Time
::setTime($now) : CRM_Utils_Time
::getTime();
1157 $mappings = self
::getMapping();
1158 foreach ($mappings as $mappingID => $mapping) {
1159 self
::buildRecipientContacts($mappingID, $now);
1160 self
::sendMailings($mappingID, $now);
1165 'messages' => ts('Sent all scheduled reminders successfully'),
1170 static function isConfigured($id, $mappingID) {
1171 $queryString = "SELECT count(id) FROM civicrm_action_schedule
1172 WHERE mapping_id = %1 AND
1176 1 => array($mappingID, 'Integer'),
1177 2 => array($id, 'Integer'),
1179 return CRM_Core_DAO
::singleValueQuery($queryString, $params);
1182 static function getRecipientListing($mappingID, $recipientType) {
1184 if (!$mappingID ||
!$recipientType) {
1188 $mapping = self
::getMapping($mappingID);
1190 switch ($mapping['entity']) {
1191 case 'civicrm_participant':
1192 $eventContacts = CRM_Core_OptionGroup
::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1193 if (!CRM_Utils_Array
::value($recipientType, $eventContacts)) {
1196 if ($eventContacts[$recipientType] == 'participant_role') {
1197 $options = CRM_Event_PseudoConstant
::participantRole();