3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * This class contains functions for managing Scheduled Reminders
21 class CRM_Core_BAO_ActionSchedule
extends CRM_Core_DAO_ActionSchedule
{
24 * @param array $filters
25 * Filter by property (e.g. 'id').
28 * Array(scalar $id => Mapping $mapping).
30 * @throws \CRM_Core_Exception
32 public static function getMappings($filters = NULL) {
33 static $_action_mapping;
35 if ($_action_mapping === NULL) {
36 $event = \Civi
::dispatcher()
37 ->dispatch('civi.actionSchedule.getMappings',
38 new \Civi\ActionSchedule\Event\
MappingRegisterEvent());
39 $_action_mapping = $event->getMappings();
42 if (empty($filters)) {
43 return $_action_mapping;
45 elseif (isset($filters['id'])) {
47 $filters['id'] => $_action_mapping[$filters['id']],
51 throw new CRM_Core_Exception("getMappings() called with unsupported filter: " . implode(', ', array_keys($filters)));
56 * @param string|int $id
57 * @return \Civi\ActionSchedule\Mapping|NULL
59 public static function getMapping($id) {
60 $mappings = self
::getMappings();
61 return $mappings[$id] ??
NULL;
65 * For each entity, get a list of entity-value labels.
68 * Ex: $entityValueLabels[$mappingId][$valueId] = $valueLabel.
69 * @throws CRM_Core_Exception
71 public static function getAllEntityValueLabels() {
72 $entityValueLabels = [];
73 foreach (CRM_Core_BAO_ActionSchedule
::getMappings() as $mapping) {
74 /** @var \Civi\ActionSchedule\Mapping $mapping */
75 $entityValueLabels[$mapping->getId()] = $mapping->getValueLabels();
76 $valueLabel = ['- ' . strtolower($mapping->getValueHeader()) . ' -'];
77 $entityValueLabels[$mapping->getId()] = $valueLabel +
$entityValueLabels[$mapping->getId()];
79 return $entityValueLabels;
83 * For each entity, get a list of entity-status labels.
86 * Ex: $entityValueLabels[$mappingId][$valueId][$statusId] = $statusLabel.
88 public static function getAllEntityStatusLabels() {
89 $entityValueLabels = self
::getAllEntityValueLabels();
90 $entityStatusLabels = [];
91 foreach (CRM_Core_BAO_ActionSchedule
::getMappings() as $mapping) {
92 /** @var \Civi\ActionSchedule\Mapping $mapping */
93 $statusLabel = ['- ' . strtolower($mapping->getStatusHeader()) . ' -'];
94 $entityStatusLabels[$mapping->getId()] = $entityValueLabels[$mapping->getId()];
95 foreach ($entityStatusLabels[$mapping->getId()] as $kkey => & $vval) {
96 $vval = $statusLabel +
$mapping->getStatusLabels($kkey);
99 return $entityStatusLabels;
103 * Retrieve list of Scheduled Reminders.
105 * @param bool $namesOnly
106 * Return simple list of names.
108 * @param \Civi\ActionSchedule\Mapping|null $filterMapping
109 * Filter by the schedule's mapping type.
110 * @param int $filterValue
111 * Filter by the schedule's entity_value.
114 * (reference) reminder list
115 * @throws \CRM_Core_Exception
117 public static function &getList($namesOnly = FALSE, $filterMapping = NULL, $filterValue = NULL) {
123 cas.entity_value as entityValueIds,
124 cas.entity_status as entityStatusIds,
125 cas.start_action_date as entityDate,
126 cas.start_action_offset,
127 cas.start_action_unit,
128 cas.start_action_condition,
133 FROM civicrm_action_schedule cas
136 $where = " WHERE 1 ";
137 if ($filterMapping and $filterValue) {
138 $where .= " AND cas.entity_value = %1 AND cas.mapping_id = %2";
139 $queryParams[1] = [$filterValue, 'Integer'];
140 $queryParams[2] = [$filterMapping->getId(), 'String'];
142 $where .= " AND cas.used_for IS NULL";
144 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
145 while ($dao->fetch()) {
146 /** @var Civi\ActionSchedule\Mapping $filterMapping */
147 $filterMapping = CRM_Utils_Array
::first(self
::getMappings([
148 'id' => $dao->mapping_id
,
150 $list[$dao->id
]['id'] = $dao->id
;
151 $list[$dao->id
]['title'] = $dao->title
;
152 $list[$dao->id
]['start_action_offset'] = $dao->start_action_offset
;
153 $list[$dao->id
]['start_action_unit'] = $dao->start_action_unit
;
154 $list[$dao->id
]['start_action_condition'] = $dao->start_action_condition
;
155 $list[$dao->id
]['entityDate'] = ucwords(str_replace('_', ' ', $dao->entityDate
));
156 $list[$dao->id
]['absolute_date'] = $dao->absolute_date
;
157 $list[$dao->id
]['entity'] = $filterMapping->getLabel();
158 $list[$dao->id
]['value'] = implode(', ', CRM_Utils_Array
::subset(
159 $filterMapping->getValueLabels(),
160 explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityValueIds
)
162 $list[$dao->id
]['status'] = implode(', ', CRM_Utils_Array
::subset(
163 $filterMapping->getStatusLabels($dao->entityValueIds
),
164 explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityStatusIds
)
166 $list[$dao->id
]['is_repeat'] = $dao->is_repeat
;
167 $list[$dao->id
]['is_active'] = $dao->is_active
;
174 * Add the schedules reminders in the db.
176 * @param array $params
177 * (reference ) an assoc array of name/value pairs.
181 * @return CRM_Core_DAO_ActionSchedule
183 public static function add(&$params, $ids = []) {
184 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
185 $actionSchedule->copyValues($params);
187 return $actionSchedule->save();
191 * Retrieve DB object based on input parameters.
193 * It also stores all the retrieved values in the default array.
195 * @param array $params
196 * (reference ) an assoc array of name/value pairs.
197 * @param array $values
198 * (reference ) an assoc array to hold the flattened values.
200 * @return CRM_Core_DAO_ActionSchedule|null
201 * object on success, null otherwise
203 public static function retrieve(&$params, &$values) {
204 if (empty($params)) {
207 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
209 $actionSchedule->copyValues($params);
211 if ($actionSchedule->find(TRUE)) {
212 $ids['actionSchedule'] = $actionSchedule->id
;
214 CRM_Core_DAO
::storeValues($actionSchedule, $values);
216 return $actionSchedule;
225 * ID of the Reminder to be deleted.
227 * @throws CRM_Core_Exception
229 public static function del($id) {
231 $dao = new CRM_Core_DAO_ActionSchedule();
233 if ($dao->find(TRUE)) {
238 throw new CRM_Core_Exception(ts('Invalid value passed to delete function.'));
242 * Update the is_active flag in the db.
245 * Id of the database record.
246 * @param bool $is_active
247 * Value we want to set the is_active field.
250 * true if we found and updated the object, else false
252 public static function setIsActive($id, $is_active) {
253 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
257 * @param int $mappingID
260 * @throws CRM_Core_Exception
262 public static function sendMailings($mappingID, $now) {
263 $mapping = CRM_Utils_Array
::first(self
::getMappings([
267 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
268 $actionSchedule->mapping_id
= $mappingID;
269 $actionSchedule->is_active
= 1;
270 $actionSchedule->find(FALSE);
272 while ($actionSchedule->fetch()) {
273 $query = CRM_Core_BAO_ActionSchedule
::prepareMailingQuery($mapping, $actionSchedule);
274 $dao = CRM_Core_DAO
::executeQuery($query,
275 [1 => [$actionSchedule->id
, 'Integer']]
278 $multilingual = CRM_Core_I18n
::isMultilingual();
279 while ($dao->fetch()) {
280 // switch language if necessary
282 $preferred_language = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $dao->contactID
, 'preferred_language');
283 CRM_Core_BAO_ActionSchedule
::setCommunicationLanguage($actionSchedule->communication_language
, $preferred_language);
288 $tokenProcessor = self
::createTokenProcessor($actionSchedule, $mapping);
289 $tokenProcessor->addRow()
290 ->context('contactId', $dao->contactID
)
291 ->context('actionSearchResult', (object) $dao->toArray());
292 foreach ($tokenProcessor->evaluate()->getRows() as $tokenRow) {
293 if ($actionSchedule->mode
== 'SMS' or $actionSchedule->mode
== 'User_Preference') {
294 CRM_Utils_Array
::extend($errors, self
::sendReminderSms($tokenRow, $actionSchedule, $dao->contactID
));
297 if ($actionSchedule->mode
== 'Email' or $actionSchedule->mode
== 'User_Preference') {
298 CRM_Utils_Array
::extend($errors, self
::sendReminderEmail($tokenRow, $actionSchedule, $dao->contactID
));
300 // insert activity log record if needed
301 if ($actionSchedule->record_activity
&& empty($errors)) {
302 $caseID = empty($dao->case_id
) ?
NULL : $dao->case_id
;
303 CRM_Core_BAO_ActionSchedule
::createMailingActivity($tokenRow, $mapping, $dao->contactID
, $dao->entityID
, $caseID);
307 catch (\Civi\Token\TokenException
$e) {
308 $errors['token_exception'] = $e->getMessage();
311 // update action log record
313 'id' => $dao->reminderID
,
314 'is_error' => !empty($errors),
315 'message' => empty($errors) ?
"null" : implode(' ', $errors),
316 'action_date_time' => $now,
318 CRM_Core_BAO_ActionLog
::create($logParams);
325 * Build a list of the contacts to send to.
327 * @param string $mappingID
328 * Value from the mapping_id field in the civicrm_action_schedule able. It might be a string like
329 * 'contribpage' for an older class like CRM_Contribute_ActionMapping_ByPage of for ones following
330 * more recent patterns, an integer.
332 * @param array $params
334 * @throws API_Exception
335 * @throws \CRM_Core_Exception
337 public static function buildRecipientContacts(string $mappingID, $now, $params = []) {
338 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
340 $actionSchedule->mapping_id
= $mappingID;
341 $actionSchedule->is_active
= 1;
342 if (!empty($params)) {
343 _civicrm_api3_dao_set_filter($actionSchedule, $params, FALSE);
345 $actionSchedule->find();
347 while ($actionSchedule->fetch()) {
348 /** @var \Civi\ActionSchedule\Mapping $mapping */
349 $mapping = CRM_Utils_Array
::first(self
::getMappings([
352 $builder = new \Civi\ActionSchedule\
RecipientBuilder($now, $actionSchedule, $mapping);
358 * Main processing callback for sending out scheduled reminders.
361 * @param array $params
363 * @throws \API_Exception
364 * @throws \CRM_Core_Exception
366 public static function processQueue($now = NULL, $params = []) {
367 $now = $now ? CRM_Utils_Time
::setTime($now) : CRM_Utils_Time
::getTime();
369 $mappings = CRM_Core_BAO_ActionSchedule
::getMappings();
370 foreach ($mappings as $mappingID => $mapping) {
371 CRM_Core_BAO_ActionSchedule
::buildRecipientContacts((string) $mappingID, $now, $params);
372 CRM_Core_BAO_ActionSchedule
::sendMailings($mappingID, $now);
378 * @param int $mappingID
380 * @return null|string
382 public static function isConfigured($id, $mappingID) {
383 $queryString = "SELECT count(id) FROM civicrm_action_schedule
384 WHERE mapping_id = %1 AND
388 1 => [$mappingID, 'String'],
389 2 => [$id, 'Integer'],
391 return CRM_Core_DAO
::singleValueQuery($queryString, $params);
395 * @param int $mappingID
396 * @param $recipientType
400 public static function getRecipientListing($mappingID, $recipientType) {
405 /** @var \Civi\ActionSchedule\Mapping $mapping */
406 $mapping = CRM_Utils_Array
::first(CRM_Core_BAO_ActionSchedule
::getMappings([
409 return $mapping->getRecipientListing($recipientType);
413 * @param $communication_language
414 * @param $preferred_language
416 public static function setCommunicationLanguage($communication_language, $preferred_language) {
417 $currentLocale = CRM_Core_I18n
::getLocale();
418 $language = $currentLocale;
420 // prepare the language for the email
421 if ($communication_language == CRM_Core_I18n
::AUTO
) {
422 if (!empty($preferred_language)) {
423 $language = $preferred_language;
427 $language = $communication_language;
430 // language not in the existing language, use default
431 $languages = CRM_Core_I18n
::languages(TRUE);
432 if (!array_key_exists($language, $languages)) {
433 $language = $currentLocale;
436 // change the language
437 $i18n = CRM_Core_I18n
::singleton();
438 $i18n->setLocale($language);
442 * Save a record about the delivery of a reminder email.
444 * WISHLIST: Instead of saving $actionSchedule->body_html, call this immediately after
445 * sending the message and pass in the fully rendered text of the message.
447 * @param object $tokenRow
448 * @param Civi\ActionSchedule\Mapping $mapping
449 * @param int $contactID
450 * @param int $entityID
451 * @param int|null $caseID
452 * @throws CRM_Core_Exception
454 protected static function createMailingActivity($tokenRow, $mapping, $contactID, $entityID, $caseID) {
455 $session = CRM_Core_Session
::singleton();
457 if ($mapping->getEntity() == 'civicrm_membership') {
458 // @todo - not required with api
460 = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Membership Renewal Reminder');
463 // @todo - not required with api
465 = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Reminder Sent');
469 'subject' => $tokenRow->render('subject'),
470 'details' => $tokenRow->render('body_html'),
471 'source_contact_id' => $session->get('userID') ?
$session->get('userID') : $contactID,
472 'target_contact_id' => $contactID,
473 // @todo - not required with api
474 'activity_date_time' => CRM_Utils_Time
::getTime('YmdHis'),
475 // @todo - not required with api
476 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
477 'activity_type_id' => $activityTypeID,
478 'source_record_id' => $entityID,
480 // @todo use api, remove all the above wrangling
481 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
483 //file reminder on case if source activity is a case activity
484 if (!empty($caseID)) {
485 $caseActivityParams = [];
486 $caseActivityParams['case_id'] = $caseID;
487 $caseActivityParams['activity_id'] = $activity->id
;
488 CRM_Case_BAO_Case
::processCaseActivity($caseActivityParams);
493 * @param \Civi\ActionSchedule\MappingInterface $mapping
494 * @param \CRM_Core_DAO_ActionSchedule $actionSchedule
497 protected static function prepareMailingQuery($mapping, $actionSchedule) {
498 $select = CRM_Utils_SQL_Select
::from('civicrm_action_log reminder')
499 ->select("reminder.id as reminderID, reminder.contact_id as contactID, reminder.entity_table as entityTable, reminder.*, e.id AS entityID")
500 ->join('e', "!casMailingJoinType !casMappingEntity e ON !casEntityJoinExpr")
501 ->select("e.id as entityID, e.*")
502 ->where("reminder.action_schedule_id = #casActionScheduleId")
503 ->where("reminder.action_date_time IS NULL")
505 'casActionScheduleId' => $actionSchedule->id
,
506 'casMailingJoinType' => ($actionSchedule->limit_to
== 0) ?
'LEFT JOIN' : 'INNER JOIN',
507 'casMappingId' => $mapping->getId(),
508 'casMappingEntity' => $mapping->getEntity(),
509 'casEntityJoinExpr' => 'e.id = reminder.entity_id',
512 if ($actionSchedule->limit_to
== 0) {
513 $select->where("e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact'");
518 'civi.actionSchedule.prepareMailingQuery',
519 new \Civi\ActionSchedule\Event\
MailingQueryEvent($actionSchedule, $mapping, $select)
522 return $select->toSQL();
526 * @param \Civi\Token\TokenRow $tokenRow
527 * @param CRM_Core_DAO_ActionSchedule $schedule
528 * @param int $toContactID
529 * @throws CRM_Core_Exception
531 * List of error messages.
533 protected static function sendReminderSms($tokenRow, $schedule, $toContactID) {
534 $toPhoneNumber = self
::pickSmsPhoneNumber($toContactID);
535 if (!$toPhoneNumber) {
536 return ["sms_phone_missing" => "Couldn't find recipient's phone number."];
539 // dev/core#369 If an SMS provider is deleted then the relevant row in the action_schedule_table is set to NULL
540 // So we need to exclude them.
541 if (CRM_Utils_System
::isNull($schedule->sms_provider_id
)) {
542 return ["sms_provider_missing" => "SMS reminder cannot be sent because the SMS provider has been deleted."];
545 $messageSubject = $tokenRow->render('subject');
546 $sms_body_text = $tokenRow->render('sms_body_text');
548 $session = CRM_Core_Session
::singleton();
549 $userID = $session->get('userID') ?
$session->get('userID') : $tokenRow->context
['contactId'];
551 'To' => $toPhoneNumber,
552 'provider_id' => $schedule->sms_provider_id
,
553 'activity_subject' => $messageSubject,
555 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS');
557 'source_contact_id' => $userID,
558 'activity_type_id' => $activityTypeID,
559 'activity_date_time' => date('YmdHis'),
560 'subject' => $messageSubject,
561 'details' => $sms_body_text,
562 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
565 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
568 CRM_Activity_BAO_Activity
::sendSMSMessage($tokenRow->context
['contactId'],
575 catch (CRM_Core_Exception
$e) {
576 return ["sms_send_error" => $e->getMessage()];
583 * @param CRM_Core_DAO_ActionSchedule $actionSchedule
585 * Ex: "Alice <alice@example.org>".
587 protected static function pickFromEmail($actionSchedule) {
588 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
589 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
590 if ($actionSchedule->from_email
) {
591 $fromEmailAddress = "$actionSchedule->from_name <$actionSchedule->from_email>";
592 return $fromEmailAddress;
594 return $fromEmailAddress;
598 * @param \Civi\Token\TokenRow $tokenRow
599 * @param CRM_Core_DAO_ActionSchedule $schedule
600 * @param int $toContactID
602 * List of error messages.
604 protected static function sendReminderEmail($tokenRow, $schedule, $toContactID) {
605 $toEmail = CRM_Contact_BAO_Contact
::getPrimaryEmail($toContactID, TRUE);
607 return ["email_missing" => "Couldn't find recipient's email address."];
610 $body_text = $tokenRow->render('body_text');
611 $body_html = $tokenRow->render('body_html');
612 if (!$schedule->body_text
) {
613 $body_text = CRM_Utils_String
::htmlToText($body_html);
616 // set up the parameters for CRM_Utils_Mail::send
618 'groupName' => 'Scheduled Reminder Sender',
619 'from' => self
::pickFromEmail($schedule),
620 'toName' => $tokenRow->context
['contact']['display_name'],
621 'toEmail' => $toEmail,
622 'subject' => $tokenRow->render('subject'),
623 'entity' => 'action_schedule',
624 'entity_id' => $schedule->id
,
627 if (!$body_html ||
$tokenRow->context
['contact']['preferred_mail_format'] == 'Text' ||
628 $tokenRow->context
['contact']['preferred_mail_format'] == 'Both'
630 // render the & entities in text mode, so that the links work
631 $mailParams['text'] = str_replace('&', '&', $body_text);
633 if ($body_html && ($tokenRow->context
['contact']['preferred_mail_format'] == 'HTML' ||
634 $tokenRow->context
['contact']['preferred_mail_format'] == 'Both'
637 $mailParams['html'] = $body_html;
639 $result = CRM_Utils_Mail
::send($mailParams);
640 if (!$result ||
is_a($result, 'PEAR_Error')) {
641 return ['email_fail' => 'Failed to send message'];
648 * @param CRM_Core_DAO_ActionSchedule $schedule
649 * @param \Civi\ActionSchedule\Mapping $mapping
650 * @return \Civi\Token\TokenProcessor
652 protected static function createTokenProcessor($schedule, $mapping) {
653 $tp = new \Civi\Token\
TokenProcessor(\Civi
::dispatcher(), [
654 'controller' => __CLASS__
,
655 'actionSchedule' => $schedule,
656 'actionMapping' => $mapping,
659 $tp->addMessage('body_text', $schedule->body_text
, 'text/plain');
660 $tp->addMessage('body_html', $schedule->body_html
, 'text/html');
661 $tp->addMessage('sms_body_text', $schedule->sms_body_text
, 'text/plain');
662 $tp->addMessage('subject', $schedule->subject
, 'text/plain');
667 * Pick SMS phone number.
669 * @param int $smsToContactId
671 * @return NULL|string
673 protected static function pickSmsPhoneNumber($smsToContactId) {
674 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($smsToContactId, FALSE, 'Mobile', [
679 //to get primary mobile ph,if not get a first mobile phONE
680 if (!empty($toPhoneNumbers)) {
681 $toPhoneNumberDetails = reset($toPhoneNumbers);
682 $toPhoneNumber = $toPhoneNumberDetails['phone'] ??
NULL;
683 return $toPhoneNumber;
689 * Get the list of generic recipient types supported by all entities/mappings.
692 * array(mixed $value => string $label).
694 public static function getAdditionalRecipients() {
696 'manual' => ts('Choose Recipient(s)'),
697 'group' => ts('Select Group'),