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
21 * This class contains functions for managing Scheduled Reminders
23 class CRM_Core_BAO_ActionSchedule
extends CRM_Core_DAO_ActionSchedule
{
26 * @param array $filters
27 * Filter by property (e.g. 'id').
30 * Array(scalar $id => Mapping $mapping).
32 * @throws \CRM_Core_Exception
34 public static function getMappings($filters = NULL) {
35 static $_action_mapping;
37 if ($_action_mapping === NULL) {
38 $event = \Civi
::dispatcher()
39 ->dispatch(\Civi\ActionSchedule\Events
::MAPPINGS
,
40 new \Civi\ActionSchedule\Event\
MappingRegisterEvent());
41 $_action_mapping = $event->getMappings();
44 if (empty($filters)) {
45 return $_action_mapping;
47 elseif (isset($filters['id'])) {
49 $filters['id'] => $_action_mapping[$filters['id']],
53 throw new CRM_Core_Exception("getMappings() called with unsupported filter: " . implode(', ', array_keys($filters)));
58 * @param string|int $id
59 * @return \Civi\ActionSchedule\Mapping|NULL
61 public static function getMapping($id) {
62 $mappings = self
::getMappings();
63 return $mappings[$id] ??
NULL;
67 * For each entity, get a list of entity-value labels.
70 * Ex: $entityValueLabels[$mappingId][$valueId] = $valueLabel.
71 * @throws CRM_Core_Exception
73 public static function getAllEntityValueLabels() {
74 $entityValueLabels = [];
75 foreach (CRM_Core_BAO_ActionSchedule
::getMappings() as $mapping) {
76 /** @var \Civi\ActionSchedule\Mapping $mapping */
77 $entityValueLabels[$mapping->getId()] = $mapping->getValueLabels();
78 $valueLabel = ['- ' . strtolower($mapping->getValueHeader()) . ' -'];
79 $entityValueLabels[$mapping->getId()] = $valueLabel +
$entityValueLabels[$mapping->getId()];
81 return $entityValueLabels;
85 * For each entity, get a list of entity-status labels.
88 * Ex: $entityValueLabels[$mappingId][$valueId][$statusId] = $statusLabel.
90 public static function getAllEntityStatusLabels() {
91 $entityValueLabels = self
::getAllEntityValueLabels();
92 $entityStatusLabels = [];
93 foreach (CRM_Core_BAO_ActionSchedule
::getMappings() as $mapping) {
94 /** @var \Civi\ActionSchedule\Mapping $mapping */
95 $statusLabel = ['- ' . strtolower($mapping->getStatusHeader()) . ' -'];
96 $entityStatusLabels[$mapping->getId()] = $entityValueLabels[$mapping->getId()];
97 foreach ($entityStatusLabels[$mapping->getId()] as $kkey => & $vval) {
98 $vval = $statusLabel +
$mapping->getStatusLabels($kkey);
101 return $entityStatusLabels;
105 * Retrieve list of Scheduled Reminders.
107 * @param bool $namesOnly
108 * Return simple list of names.
110 * @param \Civi\ActionSchedule\Mapping|null $filterMapping
111 * Filter by the schedule's mapping type.
112 * @param int $filterValue
113 * Filter by the schedule's entity_value.
116 * (reference) reminder list
117 * @throws \CRM_Core_Exception
119 public static function &getList($namesOnly = FALSE, $filterMapping = NULL, $filterValue = NULL) {
125 cas.entity_value as entityValueIds,
126 cas.entity_status as entityStatusIds,
127 cas.start_action_date as entityDate,
128 cas.start_action_offset,
129 cas.start_action_unit,
130 cas.start_action_condition,
135 FROM civicrm_action_schedule cas
138 $where = " WHERE 1 ";
139 if ($filterMapping and $filterValue) {
140 $where .= " AND cas.entity_value = %1 AND cas.mapping_id = %2";
141 $queryParams[1] = [$filterValue, 'Integer'];
142 $queryParams[2] = [$filterMapping->getId(), 'String'];
144 $where .= " AND cas.used_for IS NULL";
146 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
147 while ($dao->fetch()) {
148 /** @var Civi\ActionSchedule\Mapping $filterMapping */
149 $filterMapping = CRM_Utils_Array
::first(self
::getMappings([
150 'id' => $dao->mapping_id
,
152 $list[$dao->id
]['id'] = $dao->id
;
153 $list[$dao->id
]['title'] = $dao->title
;
154 $list[$dao->id
]['start_action_offset'] = $dao->start_action_offset
;
155 $list[$dao->id
]['start_action_unit'] = $dao->start_action_unit
;
156 $list[$dao->id
]['start_action_condition'] = $dao->start_action_condition
;
157 $list[$dao->id
]['entityDate'] = ucwords(str_replace('_', ' ', $dao->entityDate
));
158 $list[$dao->id
]['absolute_date'] = $dao->absolute_date
;
159 $list[$dao->id
]['entity'] = $filterMapping->getLabel();
160 $list[$dao->id
]['value'] = implode(', ', CRM_Utils_Array
::subset(
161 $filterMapping->getValueLabels(),
162 explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityValueIds
)
164 $list[$dao->id
]['status'] = implode(', ', CRM_Utils_Array
::subset(
165 $filterMapping->getStatusLabels($dao->entityValueIds
),
166 explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityStatusIds
)
168 $list[$dao->id
]['is_repeat'] = $dao->is_repeat
;
169 $list[$dao->id
]['is_active'] = $dao->is_active
;
176 * Add the schedules reminders in the db.
178 * @param array $params
179 * (reference ) an assoc array of name/value pairs.
183 * @return CRM_Core_DAO_ActionSchedule
185 public static function add(&$params, $ids = []) {
186 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
187 $actionSchedule->copyValues($params);
189 return $actionSchedule->save();
193 * Retrieve DB object based on input parameters.
195 * It also stores all the retrieved values in the default array.
197 * @param array $params
198 * (reference ) an assoc array of name/value pairs.
199 * @param array $values
200 * (reference ) an assoc array to hold the flattened values.
202 * @return CRM_Core_DAO_ActionSchedule|null
203 * object on success, null otherwise
205 public static function retrieve(&$params, &$values) {
206 if (empty($params)) {
209 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
211 $actionSchedule->copyValues($params);
213 if ($actionSchedule->find(TRUE)) {
214 $ids['actionSchedule'] = $actionSchedule->id
;
216 CRM_Core_DAO
::storeValues($actionSchedule, $values);
218 return $actionSchedule;
227 * ID of the Reminder to be deleted.
230 public static function del($id) {
232 $dao = new CRM_Core_DAO_ActionSchedule();
234 if ($dao->find(TRUE)) {
239 CRM_Core_Error
::fatal(ts('Invalid value passed to delete function.'));
243 * Update the is_active flag in the db.
246 * Id of the database record.
247 * @param bool $is_active
248 * Value we want to set the is_active field.
251 * true if we found and updated the object, else false
253 public static function setIsActive($id, $is_active) {
254 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
258 * @param int $mappingID
261 * @throws CRM_Core_Exception
263 public static function sendMailings($mappingID, $now) {
264 $mapping = CRM_Utils_Array
::first(self
::getMappings([
268 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
269 $actionSchedule->mapping_id
= $mappingID;
270 $actionSchedule->is_active
= 1;
271 $actionSchedule->find(FALSE);
273 while ($actionSchedule->fetch()) {
274 $query = CRM_Core_BAO_ActionSchedule
::prepareMailingQuery($mapping, $actionSchedule);
275 $dao = CRM_Core_DAO
::executeQuery($query,
276 [1 => [$actionSchedule->id
, 'Integer']]
279 $multilingual = CRM_Core_I18n
::isMultilingual();
280 while ($dao->fetch()) {
281 // switch language if necessary
283 $preferred_language = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $dao->contactID
, 'preferred_language');
284 CRM_Core_BAO_ActionSchedule
::setCommunicationLanguage($actionSchedule->communication_language
, $preferred_language);
289 $tokenProcessor = self
::createTokenProcessor($actionSchedule, $mapping);
290 $tokenProcessor->addRow()
291 ->context('contactId', $dao->contactID
)
292 ->context('actionSearchResult', (object) $dao->toArray());
293 foreach ($tokenProcessor->evaluate()->getRows() as $tokenRow) {
294 if ($actionSchedule->mode
== 'SMS' or $actionSchedule->mode
== 'User_Preference') {
295 CRM_Utils_Array
::extend($errors, self
::sendReminderSms($tokenRow, $actionSchedule, $dao->contactID
));
298 if ($actionSchedule->mode
== 'Email' or $actionSchedule->mode
== 'User_Preference') {
299 CRM_Utils_Array
::extend($errors, self
::sendReminderEmail($tokenRow, $actionSchedule, $dao->contactID
));
301 // insert activity log record if needed
302 if ($actionSchedule->record_activity
&& empty($errors)) {
303 $caseID = empty($dao->case_id
) ?
NULL : $dao->case_id
;
304 CRM_Core_BAO_ActionSchedule
::createMailingActivity($tokenRow, $mapping, $dao->contactID
, $dao->entityID
, $caseID);
308 catch (\Civi\Token\TokenException
$e) {
309 $errors['token_exception'] = $e->getMessage();
312 // update action log record
314 'id' => $dao->reminderID
,
315 'is_error' => !empty($errors),
316 'message' => empty($errors) ?
"null" : implode(' ', $errors),
317 'action_date_time' => $now,
319 CRM_Core_BAO_ActionLog
::create($logParams);
326 * Build a list of the contacts to send to.
328 * @param string $mappingID
329 * Value from the mapping_id field in the civicrm_action_schedule able. It might be a string like
330 * 'contribpage' for an older class like CRM_Contribute_ActionMapping_ByPage of for ones following
331 * more recent patterns, an integer.
333 * @param array $params
335 * @throws API_Exception
336 * @throws \CRM_Core_Exception
338 public static function buildRecipientContacts(string $mappingID, $now, $params = []) {
339 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
341 $actionSchedule->mapping_id
= $mappingID;
342 $actionSchedule->is_active
= 1;
343 if (!empty($params)) {
344 _civicrm_api3_dao_set_filter($actionSchedule, $params, FALSE);
346 $actionSchedule->find();
348 while ($actionSchedule->fetch()) {
349 /** @var \Civi\ActionSchedule\Mapping $mapping */
350 $mapping = CRM_Utils_Array
::first(self
::getMappings([
353 $builder = new \Civi\ActionSchedule\
RecipientBuilder($now, $actionSchedule, $mapping);
359 * Main processing callback for sending out scheduled reminders.
362 * @param array $params
364 * @throws \API_Exception
365 * @throws \CRM_Core_Exception
367 public static function processQueue($now = NULL, $params = []) {
368 $now = $now ? CRM_Utils_Time
::setTime($now) : CRM_Utils_Time
::getTime();
370 $mappings = CRM_Core_BAO_ActionSchedule
::getMappings();
371 foreach ($mappings as $mappingID => $mapping) {
372 CRM_Core_BAO_ActionSchedule
::buildRecipientContacts((string) $mappingID, $now, $params);
373 CRM_Core_BAO_ActionSchedule
::sendMailings($mappingID, $now);
379 * @param int $mappingID
381 * @return null|string
383 public static function isConfigured($id, $mappingID) {
384 $queryString = "SELECT count(id) FROM civicrm_action_schedule
385 WHERE mapping_id = %1 AND
389 1 => [$mappingID, 'String'],
390 2 => [$id, 'Integer'],
392 return CRM_Core_DAO
::singleValueQuery($queryString, $params);
396 * @param int $mappingID
397 * @param $recipientType
401 public static function getRecipientListing($mappingID, $recipientType) {
406 /** @var \Civi\ActionSchedule\Mapping $mapping */
407 $mapping = CRM_Utils_Array
::first(CRM_Core_BAO_ActionSchedule
::getMappings([
410 return $mapping->getRecipientListing($recipientType);
414 * @param $communication_language
415 * @param $preferred_language
417 public static function setCommunicationLanguage($communication_language, $preferred_language) {
418 $currentLocale = CRM_Core_I18n
::getLocale();
419 $language = $currentLocale;
421 // prepare the language for the email
422 if ($communication_language == CRM_Core_I18n
::AUTO
) {
423 if (!empty($preferred_language)) {
424 $language = $preferred_language;
428 $language = $communication_language;
431 // language not in the existing language, use default
432 $languages = CRM_Core_I18n
::languages(TRUE);
433 if (!array_key_exists($language, $languages)) {
434 $language = $currentLocale;
437 // change the language
438 $i18n = CRM_Core_I18n
::singleton();
439 $i18n->setLocale($language);
443 * Save a record about the delivery of a reminder email.
445 * WISHLIST: Instead of saving $actionSchedule->body_html, call this immediately after
446 * sending the message and pass in the fully rendered text of the message.
448 * @param object $tokenRow
449 * @param Civi\ActionSchedule\Mapping $mapping
450 * @param int $contactID
451 * @param int $entityID
452 * @param int|null $caseID
453 * @throws CRM_Core_Exception
455 protected static function createMailingActivity($tokenRow, $mapping, $contactID, $entityID, $caseID) {
456 $session = CRM_Core_Session
::singleton();
458 if ($mapping->getEntity() == 'civicrm_membership') {
459 // @todo - not required with api
461 = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Membership Renewal Reminder');
464 // @todo - not required with api
466 = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Reminder Sent');
470 'subject' => $tokenRow->render('subject'),
471 'details' => $tokenRow->render('body_html'),
472 'source_contact_id' => $session->get('userID') ?
$session->get('userID') : $contactID,
473 'target_contact_id' => $contactID,
474 // @todo - not required with api
475 'activity_date_time' => CRM_Utils_Time
::getTime('YmdHis'),
476 // @todo - not required with api
477 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
478 'activity_type_id' => $activityTypeID,
479 'source_record_id' => $entityID,
481 // @todo use api, remove all the above wrangling
482 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
484 //file reminder on case if source activity is a case activity
485 if (!empty($caseID)) {
486 $caseActivityParams = [];
487 $caseActivityParams['case_id'] = $caseID;
488 $caseActivityParams['activity_id'] = $activity->id
;
489 CRM_Case_BAO_Case
::processCaseActivity($caseActivityParams);
494 * @param \Civi\ActionSchedule\MappingInterface $mapping
495 * @param \CRM_Core_DAO_ActionSchedule $actionSchedule
498 protected static function prepareMailingQuery($mapping, $actionSchedule) {
499 $select = CRM_Utils_SQL_Select
::from('civicrm_action_log reminder')
500 ->select("reminder.id as reminderID, reminder.contact_id as contactID, reminder.entity_table as entityTable, reminder.*, e.id AS entityID")
501 ->join('e', "!casMailingJoinType !casMappingEntity e ON !casEntityJoinExpr")
502 ->select("e.id as entityID, e.*")
503 ->where("reminder.action_schedule_id = #casActionScheduleId")
504 ->where("reminder.action_date_time IS NULL")
506 'casActionScheduleId' => $actionSchedule->id
,
507 'casMailingJoinType' => ($actionSchedule->limit_to
== 0) ?
'LEFT JOIN' : 'INNER JOIN',
508 'casMappingId' => $mapping->getId(),
509 'casMappingEntity' => $mapping->getEntity(),
510 'casEntityJoinExpr' => 'e.id = reminder.entity_id',
513 if ($actionSchedule->limit_to
== 0) {
514 $select->where("e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact'");
519 \Civi\ActionSchedule\Events
::MAILING_QUERY
,
520 new \Civi\ActionSchedule\Event\
MailingQueryEvent($actionSchedule, $mapping, $select)
523 return $select->toSQL();
527 * @param \Civi\Token\TokenRow $tokenRow
528 * @param CRM_Core_DAO_ActionSchedule $schedule
529 * @param int $toContactID
530 * @throws CRM_Core_Exception
532 * List of error messages.
534 protected static function sendReminderSms($tokenRow, $schedule, $toContactID) {
535 $toPhoneNumber = self
::pickSmsPhoneNumber($toContactID);
536 if (!$toPhoneNumber) {
537 return ["sms_phone_missing" => "Couldn't find recipient's phone number."];
540 // dev/core#369 If an SMS provider is deleted then the relevant row in the action_schedule_table is set to NULL
541 // So we need to exclude them.
542 if (CRM_Utils_System
::isNull($schedule->sms_provider_id
)) {
543 return ["sms_provider_missing" => "SMS reminder cannot be sent because the SMS provider has been deleted."];
546 $messageSubject = $tokenRow->render('subject');
547 $sms_body_text = $tokenRow->render('sms_body_text');
549 $session = CRM_Core_Session
::singleton();
550 $userID = $session->get('userID') ?
$session->get('userID') : $tokenRow->context
['contactId'];
552 'To' => $toPhoneNumber,
553 'provider_id' => $schedule->sms_provider_id
,
554 'activity_subject' => $messageSubject,
556 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS');
558 'source_contact_id' => $userID,
559 'activity_type_id' => $activityTypeID,
560 'activity_date_time' => date('YmdHis'),
561 'subject' => $messageSubject,
562 'details' => $sms_body_text,
563 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
566 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
569 CRM_Activity_BAO_Activity
::sendSMSMessage($tokenRow->context
['contactId'],
576 catch (CRM_Core_Exception
$e) {
577 return ["sms_send_error" => $e->getMessage()];
584 * @param CRM_Core_DAO_ActionSchedule $actionSchedule
586 * Ex: "Alice <alice@example.org>".
588 protected static function pickFromEmail($actionSchedule) {
589 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
590 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
591 if ($actionSchedule->from_email
) {
592 $fromEmailAddress = "$actionSchedule->from_name <$actionSchedule->from_email>";
593 return $fromEmailAddress;
595 return $fromEmailAddress;
599 * @param \Civi\Token\TokenRow $tokenRow
600 * @param CRM_Core_DAO_ActionSchedule $schedule
601 * @param int $toContactID
603 * List of error messages.
605 protected static function sendReminderEmail($tokenRow, $schedule, $toContactID) {
606 $toEmail = CRM_Contact_BAO_Contact
::getPrimaryEmail($toContactID, TRUE);
608 return ["email_missing" => "Couldn't find recipient's email address."];
611 $body_text = $tokenRow->render('body_text');
612 $body_html = $tokenRow->render('body_html');
613 if (!$schedule->body_text
) {
614 $body_text = CRM_Utils_String
::htmlToText($body_html);
617 // set up the parameters for CRM_Utils_Mail::send
619 'groupName' => 'Scheduled Reminder Sender',
620 'from' => self
::pickFromEmail($schedule),
621 'toName' => $tokenRow->context
['contact']['display_name'],
622 'toEmail' => $toEmail,
623 'subject' => $tokenRow->render('subject'),
624 'entity' => 'action_schedule',
625 'entity_id' => $schedule->id
,
628 if (!$body_html ||
$tokenRow->context
['contact']['preferred_mail_format'] == 'Text' ||
629 $tokenRow->context
['contact']['preferred_mail_format'] == 'Both'
631 // render the & entities in text mode, so that the links work
632 $mailParams['text'] = str_replace('&', '&', $body_text);
634 if ($body_html && ($tokenRow->context
['contact']['preferred_mail_format'] == 'HTML' ||
635 $tokenRow->context
['contact']['preferred_mail_format'] == 'Both'
638 $mailParams['html'] = $body_html;
640 $result = CRM_Utils_Mail
::send($mailParams);
641 if (!$result ||
is_a($result, 'PEAR_Error')) {
642 return ['email_fail' => 'Failed to send message'];
649 * @param CRM_Core_DAO_ActionSchedule $schedule
650 * @param \Civi\ActionSchedule\Mapping $mapping
651 * @return \Civi\Token\TokenProcessor
653 protected static function createTokenProcessor($schedule, $mapping) {
654 $tp = new \Civi\Token\
TokenProcessor(\Civi
::dispatcher(), [
655 'controller' => __CLASS__
,
656 'actionSchedule' => $schedule,
657 'actionMapping' => $mapping,
660 $tp->addMessage('body_text', $schedule->body_text
, 'text/plain');
661 $tp->addMessage('body_html', $schedule->body_html
, 'text/html');
662 $tp->addMessage('sms_body_text', $schedule->sms_body_text
, 'text/plain');
663 $tp->addMessage('subject', $schedule->subject
, 'text/plain');
668 * Pick SMS phone number.
670 * @param int $smsToContactId
672 * @return NULL|string
674 protected static function pickSmsPhoneNumber($smsToContactId) {
675 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($smsToContactId, FALSE, 'Mobile', [
680 //to get primary mobile ph,if not get a first mobile phONE
681 if (!empty($toPhoneNumbers)) {
682 $toPhoneNumberDetails = reset($toPhoneNumbers);
683 $toPhoneNumber = $toPhoneNumberDetails['phone'] ??
NULL;
684 return $toPhoneNumber;
690 * Get the list of generic recipient types supported by all entities/mappings.
693 * array(mixed $value => string $label).
695 public static function getAdditionalRecipients() {
697 'manual' => ts('Choose Recipient(s)'),
698 'group' => ts('Select Group'),