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').
29 * Array(scalar $id => Mapping $mapping).
31 public static function getMappings($filters = NULL) {
32 static $_action_mapping;
34 if ($_action_mapping === NULL) {
35 $event = \Civi\Core\Container
::singleton()->get('dispatcher')
36 ->dispatch(\Civi\ActionSchedule\Events
::MAPPINGS
,
37 new \Civi\ActionSchedule\Event\
MappingRegisterEvent());
38 $_action_mapping = $event->getMappings();
41 if (empty($filters)) {
42 return $_action_mapping;
44 elseif (isset($filters['id'])) {
46 $filters['id'] => $_action_mapping[$filters['id']],
50 throw new CRM_Core_Exception("getMappings() called with unsupported filter: " . implode(', ', array_keys($filters)));
55 * @param string|int $id
56 * @return \Civi\ActionSchedule\Mapping|NULL
58 public static function getMapping($id) {
59 $mappings = self
::getMappings();
60 return isset($mappings[$id]) ?
$mappings[$id] : NULL;
64 * For each entity, get a list of entity-value labels.
67 * Ex: $entityValueLabels[$mappingId][$valueId] = $valueLabel.
68 * @throws CRM_Core_Exception
70 public static function getAllEntityValueLabels() {
71 $entityValueLabels = [];
72 foreach (CRM_Core_BAO_ActionSchedule
::getMappings() as $mapping) {
73 /** @var \Civi\ActionSchedule\Mapping $mapping */
74 $entityValueLabels[$mapping->getId()] = $mapping->getValueLabels();
75 $valueLabel = ['- ' . strtolower($mapping->getValueHeader()) . ' -'];
76 $entityValueLabels[$mapping->getId()] = $valueLabel +
$entityValueLabels[$mapping->getId()];
78 return $entityValueLabels;
82 * For each entity, get a list of entity-status labels.
85 * Ex: $entityValueLabels[$mappingId][$valueId][$statusId] = $statusLabel.
87 public static function getAllEntityStatusLabels() {
88 $entityValueLabels = self
::getAllEntityValueLabels();
89 $entityStatusLabels = [];
90 foreach (CRM_Core_BAO_ActionSchedule
::getMappings() as $mapping) {
91 /** @var \Civi\ActionSchedule\Mapping $mapping */
92 $statusLabel = ['- ' . strtolower($mapping->getStatusHeader()) . ' -'];
93 $entityStatusLabels[$mapping->getId()] = $entityValueLabels[$mapping->getId()];
94 foreach ($entityStatusLabels[$mapping->getId()] as $kkey => & $vval) {
95 $vval = $statusLabel +
$mapping->getStatusLabels($kkey);
98 return $entityStatusLabels;
102 * Retrieve list of Scheduled Reminders.
104 * @param bool $namesOnly
105 * Return simple list of names.
107 * @param \Civi\ActionSchedule\Mapping|null $filterMapping
108 * Filter by the schedule's mapping type.
109 * @param int $filterValue
110 * Filter by the schedule's entity_value.
113 * (reference) reminder list
114 * @throws \CRM_Core_Exception
116 public static function &getList($namesOnly = FALSE, $filterMapping = NULL, $filterValue = NULL) {
122 cas.entity_value as entityValueIds,
123 cas.entity_status as entityStatusIds,
124 cas.start_action_date as entityDate,
125 cas.start_action_offset,
126 cas.start_action_unit,
127 cas.start_action_condition,
132 FROM civicrm_action_schedule cas
135 $where = " WHERE 1 ";
136 if ($filterMapping and $filterValue) {
137 $where .= " AND cas.entity_value = %1 AND cas.mapping_id = %2";
138 $queryParams[1] = [$filterValue, 'Integer'];
139 $queryParams[2] = [$filterMapping->getId(), 'String'];
141 $where .= " AND cas.used_for IS NULL";
143 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
144 while ($dao->fetch()) {
145 /** @var Civi\ActionSchedule\Mapping $filterMapping */
146 $filterMapping = CRM_Utils_Array
::first(self
::getMappings([
147 'id' => $dao->mapping_id
,
149 $list[$dao->id
]['id'] = $dao->id
;
150 $list[$dao->id
]['title'] = $dao->title
;
151 $list[$dao->id
]['start_action_offset'] = $dao->start_action_offset
;
152 $list[$dao->id
]['start_action_unit'] = $dao->start_action_unit
;
153 $list[$dao->id
]['start_action_condition'] = $dao->start_action_condition
;
154 $list[$dao->id
]['entityDate'] = ucwords(str_replace('_', ' ', $dao->entityDate
));
155 $list[$dao->id
]['absolute_date'] = $dao->absolute_date
;
156 $list[$dao->id
]['entity'] = $filterMapping->getLabel();
157 $list[$dao->id
]['value'] = implode(', ', CRM_Utils_Array
::subset(
158 $filterMapping->getValueLabels(),
159 explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityValueIds
)
161 $list[$dao->id
]['status'] = implode(', ', CRM_Utils_Array
::subset(
162 $filterMapping->getStatusLabels($dao->entityValueIds
),
163 explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityStatusIds
)
165 $list[$dao->id
]['is_repeat'] = $dao->is_repeat
;
166 $list[$dao->id
]['is_active'] = $dao->is_active
;
173 * Add the schedules reminders in the db.
175 * @param array $params
176 * (reference ) an assoc array of name/value pairs.
180 * @return CRM_Core_DAO_ActionSchedule
182 public static function add(&$params, $ids = []) {
183 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
184 $actionSchedule->copyValues($params);
186 return $actionSchedule->save();
190 * Retrieve DB object based on input parameters.
192 * It also stores all the retrieved values in the default array.
194 * @param array $params
195 * (reference ) an assoc array of name/value pairs.
196 * @param array $values
197 * (reference ) an assoc array to hold the flattened values.
199 * @return CRM_Core_DAO_ActionSchedule|null
200 * object on success, null otherwise
202 public static function retrieve(&$params, &$values) {
203 if (empty($params)) {
206 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
208 $actionSchedule->copyValues($params);
210 if ($actionSchedule->find(TRUE)) {
211 $ids['actionSchedule'] = $actionSchedule->id
;
213 CRM_Core_DAO
::storeValues($actionSchedule, $values);
215 return $actionSchedule;
224 * ID of the Reminder to be deleted.
227 public static function del($id) {
229 $dao = new CRM_Core_DAO_ActionSchedule();
231 if ($dao->find(TRUE)) {
236 CRM_Core_Error
::fatal(ts('Invalid value passed to delete function.'));
240 * Update the is_active flag in the db.
243 * Id of the database record.
244 * @param bool $is_active
245 * Value we want to set the is_active field.
248 * true if we found and updated the object, else false
250 public static function setIsActive($id, $is_active) {
251 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
255 * @param int $mappingID
258 * @throws CRM_Core_Exception
260 public static function sendMailings($mappingID, $now) {
261 $mapping = CRM_Utils_Array
::first(self
::getMappings([
265 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
266 $actionSchedule->mapping_id
= $mappingID;
267 $actionSchedule->is_active
= 1;
268 $actionSchedule->find(FALSE);
270 while ($actionSchedule->fetch()) {
271 $query = CRM_Core_BAO_ActionSchedule
::prepareMailingQuery($mapping, $actionSchedule);
272 $dao = CRM_Core_DAO
::executeQuery($query,
273 [1 => [$actionSchedule->id
, 'Integer']]
276 $multilingual = CRM_Core_I18n
::isMultilingual();
277 while ($dao->fetch()) {
278 // switch language if necessary
280 $preferred_language = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $dao->contactID
, 'preferred_language');
281 CRM_Core_BAO_ActionSchedule
::setCommunicationLanguage($actionSchedule->communication_language
, $preferred_language);
286 $tokenProcessor = self
::createTokenProcessor($actionSchedule, $mapping);
287 $tokenProcessor->addRow()
288 ->context('contactId', $dao->contactID
)
289 ->context('actionSearchResult', (object) $dao->toArray());
290 foreach ($tokenProcessor->evaluate()->getRows() as $tokenRow) {
291 if ($actionSchedule->mode
== 'SMS' or $actionSchedule->mode
== 'User_Preference') {
292 CRM_Utils_Array
::extend($errors, self
::sendReminderSms($tokenRow, $actionSchedule, $dao->contactID
));
295 if ($actionSchedule->mode
== 'Email' or $actionSchedule->mode
== 'User_Preference') {
296 CRM_Utils_Array
::extend($errors, self
::sendReminderEmail($tokenRow, $actionSchedule, $dao->contactID
));
298 // insert activity log record if needed
299 if ($actionSchedule->record_activity
&& empty($errors)) {
300 $caseID = empty($dao->case_id
) ?
NULL : $dao->case_id
;
301 CRM_Core_BAO_ActionSchedule
::createMailingActivity($tokenRow, $mapping, $dao->contactID
, $dao->entityID
, $caseID);
305 catch (\Civi\Token\TokenException
$e) {
306 $errors['token_exception'] = $e->getMessage();
309 // update action log record
311 'id' => $dao->reminderID
,
312 'is_error' => !empty($errors),
313 'message' => empty($errors) ?
"null" : implode(' ', $errors),
314 'action_date_time' => $now,
316 CRM_Core_BAO_ActionLog
::create($logParams);
323 * @param int $mappingID
325 * @param array $params
327 * @throws API_Exception
329 public static function buildRecipientContacts($mappingID, $now, $params = []) {
330 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
331 $actionSchedule->mapping_id
= $mappingID;
332 $actionSchedule->is_active
= 1;
333 if (!empty($params)) {
334 _civicrm_api3_dao_set_filter($actionSchedule, $params, FALSE);
336 $actionSchedule->find();
338 while ($actionSchedule->fetch()) {
339 /** @var \Civi\ActionSchedule\Mapping $mapping */
340 $mapping = CRM_Utils_Array
::first(self
::getMappings([
343 $builder = new \Civi\ActionSchedule\
RecipientBuilder($now, $actionSchedule, $mapping);
350 * @param array $params
354 public static function processQueue($now = NULL, $params = []) {
355 $now = $now ? CRM_Utils_Time
::setTime($now) : CRM_Utils_Time
::getTime();
357 $mappings = CRM_Core_BAO_ActionSchedule
::getMappings();
358 foreach ($mappings as $mappingID => $mapping) {
359 CRM_Core_BAO_ActionSchedule
::buildRecipientContacts($mappingID, $now, $params);
360 CRM_Core_BAO_ActionSchedule
::sendMailings($mappingID, $now);
365 'messages' => ts('Sent all scheduled reminders successfully'),
372 * @param int $mappingID
374 * @return null|string
376 public static function isConfigured($id, $mappingID) {
377 $queryString = "SELECT count(id) FROM civicrm_action_schedule
378 WHERE mapping_id = %1 AND
382 1 => [$mappingID, 'String'],
383 2 => [$id, 'Integer'],
385 return CRM_Core_DAO
::singleValueQuery($queryString, $params);
389 * @param int $mappingID
390 * @param $recipientType
394 public static function getRecipientListing($mappingID, $recipientType) {
399 /** @var \Civi\ActionSchedule\Mapping $mapping */
400 $mapping = CRM_Utils_Array
::first(CRM_Core_BAO_ActionSchedule
::getMappings([
403 return $mapping->getRecipientListing($recipientType);
407 * @param $communication_language
408 * @param $preferred_language
410 public static function setCommunicationLanguage($communication_language, $preferred_language) {
411 $currentLocale = CRM_Core_I18n
::getLocale();
412 $language = $currentLocale;
414 // prepare the language for the email
415 if ($communication_language == CRM_Core_I18n
::AUTO
) {
416 if (!empty($preferred_language)) {
417 $language = $preferred_language;
421 $language = $communication_language;
424 // language not in the existing language, use default
425 $languages = CRM_Core_I18n
::languages(TRUE);
426 if (!array_key_exists($language, $languages)) {
427 $language = $currentLocale;
430 // change the language
431 $i18n = CRM_Core_I18n
::singleton();
432 $i18n->setLocale($language);
436 * Save a record about the delivery of a reminder email.
438 * WISHLIST: Instead of saving $actionSchedule->body_html, call this immediately after
439 * sending the message and pass in the fully rendered text of the message.
441 * @param object $tokenRow
442 * @param Civi\ActionSchedule\Mapping $mapping
443 * @param int $contactID
444 * @param int $entityID
445 * @param int|null $caseID
446 * @throws CRM_Core_Exception
448 protected static function createMailingActivity($tokenRow, $mapping, $contactID, $entityID, $caseID) {
449 $session = CRM_Core_Session
::singleton();
451 if ($mapping->getEntity() == 'civicrm_membership') {
452 // @todo - not required with api
454 = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Membership Renewal Reminder');
457 // @todo - not required with api
459 = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Reminder Sent');
463 'subject' => $tokenRow->render('subject'),
464 'details' => $tokenRow->render('body_html'),
465 'source_contact_id' => $session->get('userID') ?
$session->get('userID') : $contactID,
466 'target_contact_id' => $contactID,
467 // @todo - not required with api
468 'activity_date_time' => CRM_Utils_Time
::getTime('YmdHis'),
469 // @todo - not required with api
470 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
471 'activity_type_id' => $activityTypeID,
472 'source_record_id' => $entityID,
474 // @todo use api, remove all the above wrangling
475 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
477 //file reminder on case if source activity is a case activity
478 if (!empty($caseID)) {
479 $caseActivityParams = [];
480 $caseActivityParams['case_id'] = $caseID;
481 $caseActivityParams['activity_id'] = $activity->id
;
482 CRM_Case_BAO_Case
::processCaseActivity($caseActivityParams);
487 * @param \Civi\ActionSchedule\MappingInterface $mapping
488 * @param \CRM_Core_DAO_ActionSchedule $actionSchedule
491 protected static function prepareMailingQuery($mapping, $actionSchedule) {
492 $select = CRM_Utils_SQL_Select
::from('civicrm_action_log reminder')
493 ->select("reminder.id as reminderID, reminder.contact_id as contactID, reminder.entity_table as entityTable, reminder.*, e.id AS entityID")
494 ->join('e', "!casMailingJoinType !casMappingEntity e ON !casEntityJoinExpr")
495 ->select("e.id as entityID, e.*")
496 ->where("reminder.action_schedule_id = #casActionScheduleId")
497 ->where("reminder.action_date_time IS NULL")
499 'casActionScheduleId' => $actionSchedule->id
,
500 'casMailingJoinType' => ($actionSchedule->limit_to
== 0) ?
'LEFT JOIN' : 'INNER JOIN',
501 'casMappingId' => $mapping->getId(),
502 'casMappingEntity' => $mapping->getEntity(),
503 'casEntityJoinExpr' => 'e.id = reminder.entity_id',
506 if ($actionSchedule->limit_to
== 0) {
507 $select->where("e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact'");
510 \Civi\Core\Container
::singleton()->get('dispatcher')
512 \Civi\ActionSchedule\Events
::MAILING_QUERY
,
513 new \Civi\ActionSchedule\Event\
MailingQueryEvent($actionSchedule, $mapping, $select)
516 return $select->toSQL();
520 * @param \Civi\Token\TokenRow $tokenRow
521 * @param CRM_Core_DAO_ActionSchedule $schedule
522 * @param int $toContactID
523 * @throws CRM_Core_Exception
525 * List of error messages.
527 protected static function sendReminderSms($tokenRow, $schedule, $toContactID) {
528 $toPhoneNumber = self
::pickSmsPhoneNumber($toContactID);
529 if (!$toPhoneNumber) {
530 return ["sms_phone_missing" => "Couldn't find recipient's phone number."];
533 // dev/core#369 If an SMS provider is deleted then the relevant row in the action_schedule_table is set to NULL
534 // So we need to exclude them.
535 if (CRM_Utils_System
::isNull($schedule->sms_provider_id
)) {
536 return ["sms_provider_missing" => "SMS reminder cannot be sent because the SMS provider has been deleted."];
539 $messageSubject = $tokenRow->render('subject');
540 $sms_body_text = $tokenRow->render('sms_body_text');
542 $session = CRM_Core_Session
::singleton();
543 $userID = $session->get('userID') ?
$session->get('userID') : $tokenRow->context
['contactId'];
545 'To' => $toPhoneNumber,
546 'provider_id' => $schedule->sms_provider_id
,
547 'activity_subject' => $messageSubject,
549 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS');
551 'source_contact_id' => $userID,
552 'activity_type_id' => $activityTypeID,
553 'activity_date_time' => date('YmdHis'),
554 'subject' => $messageSubject,
555 'details' => $sms_body_text,
556 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
559 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
562 CRM_Activity_BAO_Activity
::sendSMSMessage($tokenRow->context
['contactId'],
569 catch (CRM_Core_Exception
$e) {
570 return ["sms_send_error" => $e->getMessage()];
577 * @param CRM_Core_DAO_ActionSchedule $actionSchedule
579 * Ex: "Alice <alice@example.org>".
581 protected static function pickFromEmail($actionSchedule) {
582 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
583 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
584 if ($actionSchedule->from_email
) {
585 $fromEmailAddress = "$actionSchedule->from_name <$actionSchedule->from_email>";
586 return $fromEmailAddress;
588 return $fromEmailAddress;
592 * @param \Civi\Token\TokenRow $tokenRow
593 * @param CRM_Core_DAO_ActionSchedule $schedule
594 * @param int $toContactID
596 * List of error messages.
598 protected static function sendReminderEmail($tokenRow, $schedule, $toContactID) {
599 $toEmail = CRM_Contact_BAO_Contact
::getPrimaryEmail($toContactID);
601 return ["email_missing" => "Couldn't find recipient's email address."];
604 $body_text = $tokenRow->render('body_text');
605 $body_html = $tokenRow->render('body_html');
606 if (!$schedule->body_text
) {
607 $body_text = CRM_Utils_String
::htmlToText($body_html);
610 // set up the parameters for CRM_Utils_Mail::send
612 'groupName' => 'Scheduled Reminder Sender',
613 'from' => self
::pickFromEmail($schedule),
614 'toName' => $tokenRow->context
['contact']['display_name'],
615 'toEmail' => $toEmail,
616 'subject' => $tokenRow->render('subject'),
617 'entity' => 'action_schedule',
618 'entity_id' => $schedule->id
,
621 if (!$body_html ||
$tokenRow->context
['contact']['preferred_mail_format'] == 'Text' ||
622 $tokenRow->context
['contact']['preferred_mail_format'] == 'Both'
624 // render the & entities in text mode, so that the links work
625 $mailParams['text'] = str_replace('&', '&', $body_text);
627 if ($body_html && ($tokenRow->context
['contact']['preferred_mail_format'] == 'HTML' ||
628 $tokenRow->context
['contact']['preferred_mail_format'] == 'Both'
631 $mailParams['html'] = $body_html;
633 $result = CRM_Utils_Mail
::send($mailParams);
634 if (!$result ||
is_a($result, 'PEAR_Error')) {
635 return ['email_fail' => 'Failed to send message'];
642 * @param CRM_Core_DAO_ActionSchedule $schedule
643 * @param \Civi\ActionSchedule\Mapping $mapping
644 * @return \Civi\Token\TokenProcessor
646 protected static function createTokenProcessor($schedule, $mapping) {
647 $tp = new \Civi\Token\
TokenProcessor(\Civi\Core\Container
::singleton()->get('dispatcher'), [
648 'controller' => __CLASS__
,
649 'actionSchedule' => $schedule,
650 'actionMapping' => $mapping,
653 $tp->addMessage('body_text', $schedule->body_text
, 'text/plain');
654 $tp->addMessage('body_html', $schedule->body_html
, 'text/html');
655 $tp->addMessage('sms_body_text', $schedule->sms_body_text
, 'text/plain');
656 $tp->addMessage('subject', $schedule->subject
, 'text/plain');
661 * Pick SMS phone number.
663 * @param int $smsToContactId
665 * @return NULL|string
667 protected static function pickSmsPhoneNumber($smsToContactId) {
668 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($smsToContactId, FALSE, 'Mobile', [
673 //to get primary mobile ph,if not get a first mobile phONE
674 if (!empty($toPhoneNumbers)) {
675 $toPhoneNumberDetails = reset($toPhoneNumbers);
676 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumberDetails);
677 return $toPhoneNumber;
683 * Get the list of generic recipient types supported by all entities/mappings.
686 * array(mixed $value => string $label).
688 public static function getAdditionalRecipients() {
690 'manual' => ts('Choose Recipient(s)'),
691 'group' => ts('Select Group'),