3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
37 * This class contains functions for managing Scheduled Reminders
39 class CRM_Core_BAO_ActionSchedule
extends CRM_Core_DAO_ActionSchedule
{
42 * @param array $filters
43 * Filter by property (e.g. 'id').
45 * Array(scalar $id => Mapping $mapping).
47 public static function getMappings($filters = NULL) {
48 static $_action_mapping;
50 if ($_action_mapping === NULL) {
51 $event = \Civi\Core\Container
::singleton()->get('dispatcher')
52 ->dispatch(\Civi\ActionSchedule\Events
::MAPPINGS
,
53 new \Civi\ActionSchedule\Event\
MappingRegisterEvent());
54 $_action_mapping = $event->getMappings();
57 if (empty($filters)) {
58 return $_action_mapping;
60 elseif (isset($filters['id'])) {
62 $filters['id'] => $_action_mapping[$filters['id']],
66 throw new CRM_Core_Exception("getMappings() called with unsupported filter: " . implode(', ', array_keys($filters)));
71 * @param string|int $id
72 * @return \Civi\ActionSchedule\Mapping|NULL
74 public static function getMapping($id) {
75 $mappings = self
::getMappings();
76 return isset($mappings[$id]) ?
$mappings[$id] : NULL;
80 * For each entity, get a list of entity-value labels.
83 * Ex: $entityValueLabels[$mappingId][$valueId] = $valueLabel.
84 * @throws CRM_Core_Exception
86 public static function getAllEntityValueLabels() {
87 $entityValueLabels = [];
88 foreach (CRM_Core_BAO_ActionSchedule
::getMappings() as $mapping) {
89 /** @var \Civi\ActionSchedule\Mapping $mapping */
90 $entityValueLabels[$mapping->getId()] = $mapping->getValueLabels();
91 $valueLabel = ['- ' . strtolower($mapping->getValueHeader()) . ' -'];
92 $entityValueLabels[$mapping->getId()] = $valueLabel +
$entityValueLabels[$mapping->getId()];
94 return $entityValueLabels;
98 * For each entity, get a list of entity-status labels.
101 * Ex: $entityValueLabels[$mappingId][$valueId][$statusId] = $statusLabel.
103 public static function getAllEntityStatusLabels() {
104 $entityValueLabels = self
::getAllEntityValueLabels();
105 $entityStatusLabels = [];
106 foreach (CRM_Core_BAO_ActionSchedule
::getMappings() as $mapping) {
107 /** @var \Civi\ActionSchedule\Mapping $mapping */
108 $statusLabel = ['- ' . strtolower($mapping->getStatusHeader()) . ' -'];
109 $entityStatusLabels[$mapping->getId()] = $entityValueLabels[$mapping->getId()];
110 foreach ($entityStatusLabels[$mapping->getId()] as $kkey => & $vval) {
111 $vval = $statusLabel +
$mapping->getStatusLabels($kkey);
114 return $entityStatusLabels;
118 * Retrieve list of Scheduled Reminders.
120 * @param bool $namesOnly
121 * Return simple list of names.
123 * @param \Civi\ActionSchedule\Mapping|null $filterMapping
124 * Filter by the schedule's mapping type.
125 * @param int $filterValue
126 * Filter by the schedule's entity_value.
129 * (reference) reminder list
130 * @throws \CRM_Core_Exception
132 public static function &getList($namesOnly = FALSE, $filterMapping = NULL, $filterValue = NULL) {
138 cas.entity_value as entityValueIds,
139 cas.entity_status as entityStatusIds,
140 cas.start_action_date as entityDate,
141 cas.start_action_offset,
142 cas.start_action_unit,
143 cas.start_action_condition,
148 FROM civicrm_action_schedule cas
151 $where = " WHERE 1 ";
152 if ($filterMapping and $filterValue) {
153 $where .= " AND cas.entity_value = %1 AND cas.mapping_id = %2";
154 $queryParams[1] = [$filterValue, 'Integer'];
155 $queryParams[2] = [$filterMapping->getId(), 'String'];
157 $where .= " AND cas.used_for IS NULL";
159 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
160 while ($dao->fetch()) {
161 /** @var Civi\ActionSchedule\Mapping $filterMapping */
162 $filterMapping = CRM_Utils_Array
::first(self
::getMappings([
163 'id' => $dao->mapping_id
,
165 $list[$dao->id
]['id'] = $dao->id
;
166 $list[$dao->id
]['title'] = $dao->title
;
167 $list[$dao->id
]['start_action_offset'] = $dao->start_action_offset
;
168 $list[$dao->id
]['start_action_unit'] = $dao->start_action_unit
;
169 $list[$dao->id
]['start_action_condition'] = $dao->start_action_condition
;
170 $list[$dao->id
]['entityDate'] = ucwords(str_replace('_', ' ', $dao->entityDate
));
171 $list[$dao->id
]['absolute_date'] = $dao->absolute_date
;
172 $list[$dao->id
]['entity'] = $filterMapping->getLabel();
173 $list[$dao->id
]['value'] = implode(', ', CRM_Utils_Array
::subset(
174 $filterMapping->getValueLabels(),
175 explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityValueIds
)
177 $list[$dao->id
]['status'] = implode(', ', CRM_Utils_Array
::subset(
178 $filterMapping->getStatusLabels($dao->entityValueIds
),
179 explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityStatusIds
)
181 $list[$dao->id
]['is_repeat'] = $dao->is_repeat
;
182 $list[$dao->id
]['is_active'] = $dao->is_active
;
189 * Add the schedules reminders in the db.
191 * @param array $params
192 * (reference ) an assoc array of name/value pairs.
196 * @return CRM_Core_DAO_ActionSchedule
198 public static function add(&$params, $ids = []) {
199 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
200 $actionSchedule->copyValues($params);
202 return $actionSchedule->save();
206 * Retrieve DB object based on input parameters.
208 * It also stores all the retrieved values in the default array.
210 * @param array $params
211 * (reference ) an assoc array of name/value pairs.
212 * @param array $values
213 * (reference ) an assoc array to hold the flattened values.
215 * @return CRM_Core_DAO_ActionSchedule|null
216 * object on success, null otherwise
218 public static function retrieve(&$params, &$values) {
219 if (empty($params)) {
222 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
224 $actionSchedule->copyValues($params);
226 if ($actionSchedule->find(TRUE)) {
227 $ids['actionSchedule'] = $actionSchedule->id
;
229 CRM_Core_DAO
::storeValues($actionSchedule, $values);
231 return $actionSchedule;
240 * ID of the Reminder to be deleted.
243 public static function del($id) {
245 $dao = new CRM_Core_DAO_ActionSchedule();
247 if ($dao->find(TRUE)) {
252 CRM_Core_Error
::fatal(ts('Invalid value passed to delete function.'));
256 * Update the is_active flag in the db.
259 * Id of the database record.
260 * @param bool $is_active
261 * Value we want to set the is_active field.
264 * true if we found and updated the object, else false
266 public static function setIsActive($id, $is_active) {
267 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
271 * @param int $mappingID
274 * @throws CRM_Core_Exception
276 public static function sendMailings($mappingID, $now) {
277 $mapping = CRM_Utils_Array
::first(self
::getMappings([
281 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
282 $actionSchedule->mapping_id
= $mappingID;
283 $actionSchedule->is_active
= 1;
284 $actionSchedule->find(FALSE);
286 while ($actionSchedule->fetch()) {
287 $query = CRM_Core_BAO_ActionSchedule
::prepareMailingQuery($mapping, $actionSchedule);
288 $dao = CRM_Core_DAO
::executeQuery($query,
289 [1 => [$actionSchedule->id
, 'Integer']]
292 $multilingual = CRM_Core_I18n
::isMultilingual();
293 while ($dao->fetch()) {
294 // switch language if necessary
296 $preferred_language = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $dao->contactID
, 'preferred_language');
297 CRM_Core_BAO_ActionSchedule
::setCommunicationLanguage($actionSchedule->communication_language
, $preferred_language);
302 $tokenProcessor = self
::createTokenProcessor($actionSchedule, $mapping);
303 $tokenProcessor->addRow()
304 ->context('contactId', $dao->contactID
)
305 ->context('actionSearchResult', (object) $dao->toArray());
306 foreach ($tokenProcessor->evaluate()->getRows() as $tokenRow) {
307 if ($actionSchedule->mode
== 'SMS' or $actionSchedule->mode
== 'User_Preference') {
308 CRM_Utils_Array
::extend($errors, self
::sendReminderSms($tokenRow, $actionSchedule, $dao->contactID
));
311 if ($actionSchedule->mode
== 'Email' or $actionSchedule->mode
== 'User_Preference') {
312 CRM_Utils_Array
::extend($errors, self
::sendReminderEmail($tokenRow, $actionSchedule, $dao->contactID
));
314 // insert activity log record if needed
315 if ($actionSchedule->record_activity
&& empty($errors)) {
316 $caseID = empty($dao->case_id
) ?
NULL : $dao->case_id
;
317 CRM_Core_BAO_ActionSchedule
::createMailingActivity($tokenRow, $mapping, $dao->contactID
, $dao->entityID
, $caseID);
321 catch (\Civi\Token\TokenException
$e) {
322 $errors['token_exception'] = $e->getMessage();
325 // update action log record
327 'id' => $dao->reminderID
,
328 'is_error' => !empty($errors),
329 'message' => empty($errors) ?
"null" : implode(' ', $errors),
330 'action_date_time' => $now,
332 CRM_Core_BAO_ActionLog
::create($logParams);
340 * @param int $mappingID
342 * @param array $params
344 * @throws API_Exception
346 public static function buildRecipientContacts($mappingID, $now, $params = []) {
347 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
348 $actionSchedule->mapping_id
= $mappingID;
349 $actionSchedule->is_active
= 1;
350 if (!empty($params)) {
351 _civicrm_api3_dao_set_filter($actionSchedule, $params, FALSE);
353 $actionSchedule->find();
355 while ($actionSchedule->fetch()) {
356 /** @var \Civi\ActionSchedule\Mapping $mapping */
357 $mapping = CRM_Utils_Array
::first(self
::getMappings([
360 $builder = new \Civi\ActionSchedule\
RecipientBuilder($now, $actionSchedule, $mapping);
367 * @param array $params
371 public static function processQueue($now = NULL, $params = []) {
372 $now = $now ? CRM_Utils_Time
::setTime($now) : CRM_Utils_Time
::getTime();
374 $mappings = CRM_Core_BAO_ActionSchedule
::getMappings();
375 foreach ($mappings as $mappingID => $mapping) {
376 CRM_Core_BAO_ActionSchedule
::buildRecipientContacts($mappingID, $now, $params);
377 CRM_Core_BAO_ActionSchedule
::sendMailings($mappingID, $now);
382 'messages' => ts('Sent all scheduled reminders successfully'),
389 * @param int $mappingID
391 * @return null|string
393 public static function isConfigured($id, $mappingID) {
394 $queryString = "SELECT count(id) FROM civicrm_action_schedule
395 WHERE mapping_id = %1 AND
399 1 => [$mappingID, 'String'],
400 2 => [$id, 'Integer'],
402 return CRM_Core_DAO
::singleValueQuery($queryString, $params);
406 * @param int $mappingID
407 * @param $recipientType
411 public static function getRecipientListing($mappingID, $recipientType) {
416 /** @var \Civi\ActionSchedule\Mapping $mapping */
417 $mapping = CRM_Utils_Array
::first(CRM_Core_BAO_ActionSchedule
::getMappings([
420 return $mapping->getRecipientListing($recipientType);
424 * @param $communication_language
425 * @param $preferred_language
427 public static function setCommunicationLanguage($communication_language, $preferred_language) {
428 $currentLocale = CRM_Core_I18n
::getLocale();
429 $language = $currentLocale;
431 // prepare the language for the email
432 if ($communication_language == CRM_Core_I18n
::AUTO
) {
433 if (!empty($preferred_language)) {
434 $language = $preferred_language;
438 $language = $communication_language;
441 // language not in the existing language, use default
442 $languages = CRM_Core_I18n
::languages(TRUE);
443 if (!array_key_exists($language, $languages)) {
444 $language = $currentLocale;
447 // change the language
448 $i18n = CRM_Core_I18n
::singleton();
449 $i18n->setLocale($language);
453 * Save a record about the delivery of a reminder email.
455 * WISHLIST: Instead of saving $actionSchedule->body_html, call this immediately after
456 * sending the message and pass in the fully rendered text of the message.
458 * @param object $tokenRow
459 * @param Civi\ActionSchedule\Mapping $mapping
460 * @param int $contactID
461 * @param int $entityID
462 * @param int|null $caseID
463 * @throws CRM_Core_Exception
465 protected static function createMailingActivity($tokenRow, $mapping, $contactID, $entityID, $caseID) {
466 $session = CRM_Core_Session
::singleton();
468 if ($mapping->getEntity() == 'civicrm_membership') {
469 // @todo - not required with api
471 = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Membership Renewal Reminder');
474 // @todo - not required with api
476 = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Reminder Sent');
480 'subject' => $tokenRow->render('subject'),
481 'details' => $tokenRow->render('body_html'),
482 'source_contact_id' => $session->get('userID') ?
$session->get('userID') : $contactID,
483 'target_contact_id' => $contactID,
484 // @todo - not required with api
485 'activity_date_time' => CRM_Utils_Time
::getTime('YmdHis'),
486 // @todo - not required with api
487 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
488 'activity_type_id' => $activityTypeID,
489 'source_record_id' => $entityID,
491 // @todo use api, remove all the above wrangling
492 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
494 //file reminder on case if source activity is a case activity
495 if (!empty($caseID)) {
496 $caseActivityParams = [];
497 $caseActivityParams['case_id'] = $caseID;
498 $caseActivityParams['activity_id'] = $activity->id
;
499 CRM_Case_BAO_Case
::processCaseActivity($caseActivityParams);
504 * @param \Civi\ActionSchedule\MappingInterface $mapping
505 * @param \CRM_Core_DAO_ActionSchedule $actionSchedule
508 protected static function prepareMailingQuery($mapping, $actionSchedule) {
509 $select = CRM_Utils_SQL_Select
::from('civicrm_action_log reminder')
510 ->select("reminder.id as reminderID, reminder.contact_id as contactID, reminder.entity_table as entityTable, reminder.*, e.id AS entityID")
511 ->join('e', "!casMailingJoinType !casMappingEntity e ON !casEntityJoinExpr")
512 ->select("e.id as entityID, e.*")
513 ->where("reminder.action_schedule_id = #casActionScheduleId")
514 ->where("reminder.action_date_time IS NULL")
516 'casActionScheduleId' => $actionSchedule->id
,
517 'casMailingJoinType' => ($actionSchedule->limit_to
== 0) ?
'LEFT JOIN' : 'INNER JOIN',
518 'casMappingId' => $mapping->getId(),
519 'casMappingEntity' => $mapping->getEntity(),
520 'casEntityJoinExpr' => 'e.id = reminder.entity_id',
523 if ($actionSchedule->limit_to
== 0) {
524 $select->where("e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact'");
527 \Civi\Core\Container
::singleton()->get('dispatcher')
529 \Civi\ActionSchedule\Events
::MAILING_QUERY
,
530 new \Civi\ActionSchedule\Event\
MailingQueryEvent($actionSchedule, $mapping, $select)
533 return $select->toSQL();
537 * @param \Civi\Token\TokenRow $tokenRow
538 * @param CRM_Core_DAO_ActionSchedule $schedule
539 * @param int $toContactID
540 * @throws CRM_Core_Exception
542 * List of error messages.
544 protected static function sendReminderSms($tokenRow, $schedule, $toContactID) {
545 $toPhoneNumber = self
::pickSmsPhoneNumber($toContactID);
546 if (!$toPhoneNumber) {
547 return ["sms_phone_missing" => "Couldn't find recipient's phone number."];
550 // dev/core#369 If an SMS provider is deleted then the relevant row in the action_schedule_table is set to NULL
551 // So we need to exclude them.
552 if (CRM_Utils_System
::isNull($schedule->sms_provider_id
)) {
553 return ["sms_provider_missing" => "SMS reminder cannot be sent because the SMS provider has been deleted."];
556 $messageSubject = $tokenRow->render('subject');
557 $sms_body_text = $tokenRow->render('sms_body_text');
559 $session = CRM_Core_Session
::singleton();
560 $userID = $session->get('userID') ?
$session->get('userID') : $tokenRow->context
['contactId'];
562 'To' => $toPhoneNumber,
563 'provider_id' => $schedule->sms_provider_id
,
564 'activity_subject' => $messageSubject,
566 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS');
568 'source_contact_id' => $userID,
569 'activity_type_id' => $activityTypeID,
570 'activity_date_time' => date('YmdHis'),
571 'subject' => $messageSubject,
572 'details' => $sms_body_text,
573 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
576 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
578 CRM_Activity_BAO_Activity
::sendSMSMessage($tokenRow->context
['contactId'],
589 * @param CRM_Core_DAO_ActionSchedule $actionSchedule
591 * Ex: "Alice <alice@example.org>".
593 protected static function pickFromEmail($actionSchedule) {
594 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
595 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
596 if ($actionSchedule->from_email
) {
597 $fromEmailAddress = "$actionSchedule->from_name <$actionSchedule->from_email>";
598 return $fromEmailAddress;
600 return $fromEmailAddress;
604 * @param \Civi\Token\TokenRow $tokenRow
605 * @param CRM_Core_DAO_ActionSchedule $schedule
606 * @param int $toContactID
608 * List of error messages.
610 protected static function sendReminderEmail($tokenRow, $schedule, $toContactID) {
611 $toEmail = CRM_Contact_BAO_Contact
::getPrimaryEmail($toContactID);
613 return ["email_missing" => "Couldn't find recipient's email address."];
616 $body_text = $tokenRow->render('body_text');
617 $body_html = $tokenRow->render('body_html');
618 if (!$schedule->body_text
) {
619 $body_text = CRM_Utils_String
::htmlToText($body_html);
622 // set up the parameters for CRM_Utils_Mail::send
624 'groupName' => 'Scheduled Reminder Sender',
625 'from' => self
::pickFromEmail($schedule),
626 'toName' => $tokenRow->context
['contact']['display_name'],
627 'toEmail' => $toEmail,
628 'subject' => $tokenRow->render('subject'),
629 'entity' => 'action_schedule',
630 'entity_id' => $schedule->id
,
633 if (!$body_html ||
$tokenRow->context
['contact']['preferred_mail_format'] == 'Text' ||
634 $tokenRow->context
['contact']['preferred_mail_format'] == 'Both'
636 // render the & entities in text mode, so that the links work
637 $mailParams['text'] = str_replace('&', '&', $body_text);
639 if ($body_html && ($tokenRow->context
['contact']['preferred_mail_format'] == 'HTML' ||
640 $tokenRow->context
['contact']['preferred_mail_format'] == 'Both'
643 $mailParams['html'] = $body_html;
645 $result = CRM_Utils_Mail
::send($mailParams);
646 if (!$result ||
is_a($result, 'PEAR_Error')) {
647 return ['email_fail' => 'Failed to send message'];
654 * @param CRM_Core_DAO_ActionSchedule $schedule
655 * @param \Civi\ActionSchedule\Mapping $mapping
656 * @return \Civi\Token\TokenProcessor
658 protected static function createTokenProcessor($schedule, $mapping) {
659 $tp = new \Civi\Token\
TokenProcessor(\Civi\Core\Container
::singleton()->get('dispatcher'), [
660 'controller' => __CLASS__
,
661 'actionSchedule' => $schedule,
662 'actionMapping' => $mapping,
665 $tp->addMessage('body_text', $schedule->body_text
, 'text/plain');
666 $tp->addMessage('body_html', $schedule->body_html
, 'text/html');
667 $tp->addMessage('sms_body_text', $schedule->sms_body_text
, 'text/plain');
668 $tp->addMessage('subject', $schedule->subject
, 'text/plain');
673 * Pick SMS phone number.
675 * @param int $smsToContactId
677 * @return NULL|string
679 protected static function pickSmsPhoneNumber($smsToContactId) {
680 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($smsToContactId, FALSE, 'Mobile', [
685 //to get primary mobile ph,if not get a first mobile phONE
686 if (!empty($toPhoneNumbers)) {
687 $toPhoneNumberDetails = reset($toPhoneNumbers);
688 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumberDetails);
689 return $toPhoneNumber;
695 * Get the list of generic recipient types supported by all entities/mappings.
698 * array(mixed $value => string $label).
700 public static function getAdditionalRecipients() {
702 'manual' => ts('Choose Recipient(s)'),
703 'group' => ts('Select Group'),