Merge pull request #20239 from eileenmcnaughton/act
[civicrm-core.git] / CRM / Core / BAO / ActionSchedule.php
CommitLineData
6a488035
TO
1<?php
2/*
bc77d7c0
TO
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
006389de 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
20f48505 18use Civi\ActionSchedule\Event\MappingRegisterEvent;
19
6a488035
TO
20/**
21 * This class contains functions for managing Scheduled Reminders
22 */
23class CRM_Core_BAO_ActionSchedule extends CRM_Core_DAO_ActionSchedule {
24
b5c2afd0 25 /**
50a23755 26 * @param array $filters
9e1bf145 27 * Filter by property (e.g. 'id').
4162ab6f 28 *
b5c2afd0 29 * @return array
50a23755 30 * Array(scalar $id => Mapping $mapping).
2e9914a0 31 *
4162ab6f 32 * @throws \CRM_Core_Exception
b5c2afd0 33 */
50a23755 34 public static function getMappings($filters = NULL) {
6a488035
TO
35 static $_action_mapping;
36
50a23755 37 if ($_action_mapping === NULL) {
4162ab6f 38 $event = \Civi::dispatcher()
bc2feeb1 39 ->dispatch('civi.actionSchedule.getMappings',
20f48505 40 new MappingRegisterEvent());
9c8748cc 41 $_action_mapping = $event->getMappings();
6a488035
TO
42 }
43
9e1bf145 44 if (empty($filters)) {
50a23755 45 return $_action_mapping;
6a488035 46 }
20f48505 47 if (isset($filters['id'])) {
48 return [$filters['id'] => $_action_mapping[$filters['id']]];
8d657dde 49 }
20f48505 50 throw new CRM_Core_Exception("getMappings() called with unsupported filter: " . implode(', ', array_keys($filters)));
8d657dde
AH
51 }
52
7f0141d8
TO
53 /**
54 * @param string|int $id
20f48505 55 *
7f0141d8 56 * @return \Civi\ActionSchedule\Mapping|NULL
20f48505 57 * @throws \CRM_Core_Exception
7f0141d8
TO
58 */
59 public static function getMapping($id) {
60 $mappings = self::getMappings();
2e1f50d6 61 return $mappings[$id] ?? NULL;
7f0141d8
TO
62 }
63
6a488035 64 /**
0905ee5d 65 * For each entity, get a list of entity-value labels.
6a488035 66 *
a6c01b45 67 * @return array
0905ee5d
TO
68 * Ex: $entityValueLabels[$mappingId][$valueId] = $valueLabel.
69 * @throws CRM_Core_Exception
6a488035 70 */
0905ee5d 71 public static function getAllEntityValueLabels() {
be2fb01f 72 $entityValueLabels = [];
0905ee5d 73 foreach (CRM_Core_BAO_ActionSchedule::getMappings() as $mapping) {
50a23755 74 /** @var \Civi\ActionSchedule\Mapping $mapping */
d3600e68 75 $entityValueLabels[$mapping->getId()] = $mapping->getValueLabels();
be2fb01f 76 $valueLabel = ['- ' . strtolower($mapping->getValueHeader()) . ' -'];
018d5e02 77 $entityValueLabels[$mapping->getId()] = $valueLabel + $entityValueLabels[$mapping->getId()];
d3600e68 78 }
0905ee5d
TO
79 return $entityValueLabels;
80 }
6a488035 81
0905ee5d
TO
82 /**
83 * For each entity, get a list of entity-status labels.
84 *
85 * @return array
86 * Ex: $entityValueLabels[$mappingId][$valueId][$statusId] = $statusLabel.
87 */
88 public static function getAllEntityStatusLabels() {
89 $entityValueLabels = self::getAllEntityValueLabels();
be2fb01f 90 $entityStatusLabels = [];
0905ee5d 91 foreach (CRM_Core_BAO_ActionSchedule::getMappings() as $mapping) {
d3600e68 92 /** @var \Civi\ActionSchedule\Mapping $mapping */
be2fb01f 93 $statusLabel = ['- ' . strtolower($mapping->getStatusHeader()) . ' -'];
9e1bf145
TO
94 $entityStatusLabels[$mapping->getId()] = $entityValueLabels[$mapping->getId()];
95 foreach ($entityStatusLabels[$mapping->getId()] as $kkey => & $vval) {
50a23755 96 $vval = $statusLabel + $mapping->getStatusLabels($kkey);
6a488035
TO
97 }
98 }
0905ee5d 99 return $entityStatusLabels;
6a488035
TO
100 }
101
102 /**
fe482240 103 * Retrieve list of Scheduled Reminders.
6a488035 104 *
9d451db8 105 * @param \Civi\ActionSchedule\Mapping|null $filterMapping
77e16391
TO
106 * Filter by the schedule's mapping type.
107 * @param int $filterValue
108 * Filter by the schedule's entity_value.
6a488035 109 *
a6c01b45
CW
110 * @return array
111 * (reference) reminder list
9d451db8 112 * @throws \CRM_Core_Exception
6a488035 113 */
987e3a4f 114 public static function getList($filterMapping = NULL, $filterValue = NULL): array {
115 $list = [];
6a488035
TO
116 $query = "
117SELECT
118 title,
6a488035 119 cas.id as id,
50a23755 120 cas.mapping_id,
6a488035 121 cas.entity_value as entityValueIds,
6a488035
TO
122 cas.entity_status as entityStatusIds,
123 cas.start_action_date as entityDate,
124 cas.start_action_offset,
125 cas.start_action_unit,
126 cas.start_action_condition,
127 cas.absolute_date,
128 is_repeat,
129 is_active
130
131FROM civicrm_action_schedule cas
6a488035 132";
be2fb01f 133 $queryParams = [];
62933949 134 $where = " WHERE 1 ";
77e16391
TO
135 if ($filterMapping and $filterValue) {
136 $where .= " AND cas.entity_value = %1 AND cas.mapping_id = %2";
be2fb01f
CW
137 $queryParams[1] = [$filterValue, 'Integer'];
138 $queryParams[2] = [$filterMapping->getId(), 'String'];
6a488035 139 }
62933949 140 $where .= " AND cas.used_for IS NULL";
141 $query .= $where;
50a23755 142 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
6a488035 143 while ($dao->fetch()) {
77e16391 144 /** @var Civi\ActionSchedule\Mapping $filterMapping */
be2fb01f 145 $filterMapping = CRM_Utils_Array::first(self::getMappings([
50a23755 146 'id' => $dao->mapping_id,
be2fb01f 147 ]));
6a488035
TO
148 $list[$dao->id]['id'] = $dao->id;
149 $list[$dao->id]['title'] = $dao->title;
150 $list[$dao->id]['start_action_offset'] = $dao->start_action_offset;
151 $list[$dao->id]['start_action_unit'] = $dao->start_action_unit;
152 $list[$dao->id]['start_action_condition'] = $dao->start_action_condition;
153 $list[$dao->id]['entityDate'] = ucwords(str_replace('_', ' ', $dao->entityDate));
154 $list[$dao->id]['absolute_date'] = $dao->absolute_date;
9e1bf145 155 $list[$dao->id]['entity'] = $filterMapping->getLabel();
50a23755 156 $list[$dao->id]['value'] = implode(', ', CRM_Utils_Array::subset(
77e16391 157 $filterMapping->getValueLabels(),
50a23755
TO
158 explode(CRM_Core_DAO::VALUE_SEPARATOR, $dao->entityValueIds)
159 ));
160 $list[$dao->id]['status'] = implode(', ', CRM_Utils_Array::subset(
77e16391 161 $filterMapping->getStatusLabels($dao->entityValueIds),
50a23755
TO
162 explode(CRM_Core_DAO::VALUE_SEPARATOR, $dao->entityStatusIds)
163 ));
6a488035
TO
164 $list[$dao->id]['is_repeat'] = $dao->is_repeat;
165 $list[$dao->id]['is_active'] = $dao->is_active;
166 }
167
168 return $list;
169 }
170
6a488035 171 /**
85ddbcc0 172 * Add the scheduled reminders in the db.
6a488035 173 *
6a0b768e 174 * @param array $params
85ddbcc0 175 * An assoc array of name/value pairs.
6a488035 176 *
c490a46a 177 * @return CRM_Core_DAO_ActionSchedule
85ddbcc0 178 * @throws \CRM_Core_Exception
6a488035 179 */
85ddbcc0 180 public static function add(array $params): CRM_Core_DAO_ActionSchedule {
181 return self::writeRecord($params);
6a488035
TO
182 }
183
184 /**
fe482240
EM
185 * Retrieve DB object based on input parameters.
186 *
187 * It also stores all the retrieved values in the default array.
6a488035 188 *
6a0b768e
TO
189 * @param array $params
190 * (reference ) an assoc array of name/value pairs.
191 * @param array $values
192 * (reference ) an assoc array to hold the flattened values.
6a488035 193 *
16b10e64
CW
194 * @return CRM_Core_DAO_ActionSchedule|null
195 * object on success, null otherwise
6a488035 196 */
00be9182 197 public static function retrieve(&$params, &$values) {
6a488035
TO
198 if (empty($params)) {
199 return NULL;
200 }
201 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
202
203 $actionSchedule->copyValues($params);
204
205 if ($actionSchedule->find(TRUE)) {
6a488035 206 CRM_Core_DAO::storeValues($actionSchedule, $values);
6a488035
TO
207 return $actionSchedule;
208 }
209 return NULL;
210 }
211
212 /**
fe482240 213 * Delete a Reminder.
6a488035 214 *
6a0b768e
TO
215 * @param int $id
216 * ID of the Reminder to be deleted.
6a488035 217 *
ac15829d 218 * @throws CRM_Core_Exception
6a488035 219 */
00be9182 220 public static function del($id) {
6a488035
TO
221 if ($id) {
222 $dao = new CRM_Core_DAO_ActionSchedule();
223 $dao->id = $id;
224 if ($dao->find(TRUE)) {
225 $dao->delete();
226 return;
227 }
228 }
ac15829d 229 throw new CRM_Core_Exception(ts('Invalid value passed to delete function.'));
6a488035
TO
230 }
231
232 /**
fe482240 233 * Update the is_active flag in the db.
6a488035 234 *
6a0b768e
TO
235 * @param int $id
236 * Id of the database record.
237 * @param bool $is_active
238 * Value we want to set the is_active field.
6a488035 239 *
8a4fede3 240 * @return bool
241 * true if we found and updated the object, else false
6a488035 242 */
00be9182 243 public static function setIsActive($id, $is_active) {
6a488035
TO
244 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
245 }
246
b5c2afd0 247 /**
100fef9d 248 * @param int $mappingID
b5c2afd0
EM
249 * @param $now
250 *
251 * @throws CRM_Core_Exception
252 */
00be9182 253 public static function sendMailings($mappingID, $now) {
be2fb01f 254 $mapping = CRM_Utils_Array::first(self::getMappings([
50a23755 255 'id' => $mappingID,
be2fb01f 256 ]));
6a488035
TO
257
258 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
259 $actionSchedule->mapping_id = $mappingID;
260 $actionSchedule->is_active = 1;
261 $actionSchedule->find(FALSE);
262
6a488035 263 while ($actionSchedule->fetch()) {
5b16d8b6 264 $query = CRM_Core_BAO_ActionSchedule::prepareMailingQuery($mapping, $actionSchedule);
6a488035 265 $dao = CRM_Core_DAO::executeQuery($query,
be2fb01f 266 [1 => [$actionSchedule->id, 'Integer']]
6a488035
TO
267 );
268
07844ccf 269 $multilingual = CRM_Core_I18n::isMultilingual();
6a488035 270 while ($dao->fetch()) {
07844ccf
SV
271 // switch language if necessary
272 if ($multilingual) {
c72ba2be 273 $preferred_language = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $dao->contactID, 'preferred_language');
07844ccf
SV
274 CRM_Core_BAO_ActionSchedule::setCommunicationLanguage($actionSchedule->communication_language, $preferred_language);
275 }
276
be2fb01f 277 $errors = [];
d22bcd5b 278 try {
50a23755 279 $tokenProcessor = self::createTokenProcessor($actionSchedule, $mapping);
d22bcd5b
TO
280 $tokenProcessor->addRow()
281 ->context('contactId', $dao->contactID)
50a23755 282 ->context('actionSearchResult', (object) $dao->toArray());
d22bcd5b 283 foreach ($tokenProcessor->evaluate()->getRows() as $tokenRow) {
20f48505 284 if ($actionSchedule->mode === 'SMS' || $actionSchedule->mode === 'User_Preference') {
d22bcd5b 285 CRM_Utils_Array::extend($errors, self::sendReminderSms($tokenRow, $actionSchedule, $dao->contactID));
43ceab3f 286 }
6a488035 287
20f48505 288 if ($actionSchedule->mode === 'Email' || $actionSchedule->mode === 'User_Preference') {
d22bcd5b 289 CRM_Utils_Array::extend($errors, self::sendReminderEmail($tokenRow, $actionSchedule, $dao->contactID));
43ceab3f 290 }
d19632b1
JP
291 // insert activity log record if needed
292 if ($actionSchedule->record_activity && empty($errors)) {
293 $caseID = empty($dao->case_id) ? NULL : $dao->case_id;
294 CRM_Core_BAO_ActionSchedule::createMailingActivity($tokenRow, $mapping, $dao->contactID, $dao->entityID, $caseID);
295 }
43ceab3f 296 }
6a488035 297 }
d22bcd5b
TO
298 catch (\Civi\Token\TokenException $e) {
299 $errors['token_exception'] = $e->getMessage();
6a488035
TO
300 }
301
302 // update action log record
be2fb01f 303 $logParams = [
6a488035 304 'id' => $dao->reminderID,
d22bcd5b
TO
305 'is_error' => !empty($errors),
306 'message' => empty($errors) ? "null" : implode(' ', $errors),
6a488035 307 'action_date_time' => $now,
be2fb01f 308 ];
6a488035 309 CRM_Core_BAO_ActionLog::create($logParams);
6a488035
TO
310 }
311
6a488035
TO
312 }
313 }
314
b5c2afd0 315 /**
2e9914a0 316 * Build a list of the contacts to send to.
317 *
318 * @param string $mappingID
319 * Value from the mapping_id field in the civicrm_action_schedule able. It might be a string like
320 * 'contribpage' for an older class like CRM_Contribute_ActionMapping_ByPage of for ones following
321 * more recent patterns, an integer.
322 * @param string $now
b5c2afd0
EM
323 * @param array $params
324 *
325 * @throws API_Exception
2e9914a0 326 * @throws \CRM_Core_Exception
b5c2afd0 327 */
2e9914a0 328 public static function buildRecipientContacts(string $mappingID, $now, $params = []) {
6a488035 329 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
2e9914a0 330
6a488035
TO
331 $actionSchedule->mapping_id = $mappingID;
332 $actionSchedule->is_active = 1;
22e263ad 333 if (!empty($params)) {
244bbdd8 334 _civicrm_api3_dao_set_filter($actionSchedule, $params, FALSE);
73f3e293 335 }
6a488035
TO
336 $actionSchedule->find();
337
338 while ($actionSchedule->fetch()) {
77e16391 339 /** @var \Civi\ActionSchedule\Mapping $mapping */
be2fb01f 340 $mapping = CRM_Utils_Array::first(self::getMappings([
50a23755 341 'id' => $mappingID,
be2fb01f 342 ]));
c09bacfd
TO
343 $builder = new \Civi\ActionSchedule\RecipientBuilder($now, $actionSchedule, $mapping);
344 $builder->build();
6a488035
TO
345 }
346 }
347
b5c2afd0 348 /**
2e9914a0 349 * Main processing callback for sending out scheduled reminders.
350 *
351 * @param string $now
b5c2afd0
EM
352 * @param array $params
353 *
2e9914a0 354 * @throws \API_Exception
355 * @throws \CRM_Core_Exception
b5c2afd0 356 */
87fa0491 357 public static function processQueue($now = NULL, $params = []): void {
6a488035
TO
358 $now = $now ? CRM_Utils_Time::setTime($now) : CRM_Utils_Time::getTime();
359
50a23755 360 $mappings = CRM_Core_BAO_ActionSchedule::getMappings();
6a488035 361 foreach ($mappings as $mappingID => $mapping) {
2e9914a0 362 CRM_Core_BAO_ActionSchedule::buildRecipientContacts((string) $mappingID, $now, $params);
5b16d8b6 363 CRM_Core_BAO_ActionSchedule::sendMailings($mappingID, $now);
6a488035 364 }
6a488035
TO
365 }
366
9a4df24c 367 /**
100fef9d
CW
368 * @param int $id
369 * @param int $mappingID
9a4df24c
EM
370 *
371 * @return null|string
372 */
00be9182 373 public static function isConfigured($id, $mappingID) {
6a488035
TO
374 $queryString = "SELECT count(id) FROM civicrm_action_schedule
375 WHERE mapping_id = %1 AND
376 entity_value = %2";
377
be2fb01f
CW
378 $params = [
379 1 => [$mappingID, 'String'],
380 2 => [$id, 'Integer'],
381 ];
6a488035
TO
382 return CRM_Core_DAO::singleValueQuery($queryString, $params);
383 }
384
b5c2afd0 385 /**
100fef9d 386 * @param int $mappingID
b5c2afd0
EM
387 * @param $recipientType
388 *
389 * @return array
390 */
00be9182 391 public static function getRecipientListing($mappingID, $recipientType) {
77e16391 392 if (!$mappingID) {
be2fb01f 393 return [];
6a488035
TO
394 }
395
77e16391 396 /** @var \Civi\ActionSchedule\Mapping $mapping */
be2fb01f 397 $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
50a23755 398 'id' => $mappingID,
be2fb01f 399 ]));
77e16391 400 return $mapping->getRecipientListing($recipientType);
6a488035 401 }
96025800 402
07844ccf
SV
403 /**
404 * @param $communication_language
405 * @param $preferred_language
406 */
407 public static function setCommunicationLanguage($communication_language, $preferred_language) {
c86241f4 408 $currentLocale = CRM_Core_I18n::getLocale();
8ea23016 409 $language = $currentLocale;
fadd4d37 410
07844ccf
SV
411 // prepare the language for the email
412 if ($communication_language == CRM_Core_I18n::AUTO) {
413 if (!empty($preferred_language)) {
414 $language = $preferred_language;
415 }
416 }
417 else {
418 $language = $communication_language;
419 }
420
421 // language not in the existing language, use default
273f9849 422 $languages = CRM_Core_I18n::languages(TRUE);
8ea23016
SV
423 if (!array_key_exists($language, $languages)) {
424 $language = $currentLocale;
07844ccf
SV
425 }
426
427 // change the language
e8576142 428 $i18n = CRM_Core_I18n::singleton();
8ea23016 429 $i18n->setLocale($language);
07844ccf
SV
430 }
431
c72ba2be
TO
432 /**
433 * Save a record about the delivery of a reminder email.
434 *
435 * WISHLIST: Instead of saving $actionSchedule->body_html, call this immediately after
436 * sending the message and pass in the fully rendered text of the message.
437 *
d19632b1 438 * @param object $tokenRow
50a23755 439 * @param Civi\ActionSchedule\Mapping $mapping
c72ba2be
TO
440 * @param int $contactID
441 * @param int $entityID
e97c66ff 442 * @param int|null $caseID
c72ba2be
TO
443 * @throws CRM_Core_Exception
444 */
d19632b1 445 protected static function createMailingActivity($tokenRow, $mapping, $contactID, $entityID, $caseID) {
c72ba2be
TO
446 $session = CRM_Core_Session::singleton();
447
9e1bf145 448 if ($mapping->getEntity() == 'civicrm_membership') {
d66c61b6 449 // @todo - not required with api
c72ba2be 450 $activityTypeID
d66c61b6 451 = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Membership Renewal Reminder');
c72ba2be
TO
452 }
453 else {
d66c61b6 454 // @todo - not required with api
c72ba2be 455 $activityTypeID
d66c61b6 456 = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Reminder Sent');
c72ba2be
TO
457 }
458
be2fb01f 459 $activityParams = [
d19632b1
JP
460 'subject' => $tokenRow->render('subject'),
461 'details' => $tokenRow->render('body_html'),
c72ba2be
TO
462 'source_contact_id' => $session->get('userID') ? $session->get('userID') : $contactID,
463 'target_contact_id' => $contactID,
d66c61b6 464 // @todo - not required with api
c72ba2be 465 'activity_date_time' => CRM_Utils_Time::getTime('YmdHis'),
d66c61b6 466 // @todo - not required with api
467 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
c72ba2be
TO
468 'activity_type_id' => $activityTypeID,
469 'source_record_id' => $entityID,
be2fb01f 470 ];
d66c61b6 471 // @todo use api, remove all the above wrangling
c72ba2be
TO
472 $activity = CRM_Activity_BAO_Activity::create($activityParams);
473
474 //file reminder on case if source activity is a case activity
475 if (!empty($caseID)) {
be2fb01f 476 $caseActivityParams = [];
c72ba2be
TO
477 $caseActivityParams['case_id'] = $caseID;
478 $caseActivityParams['activity_id'] = $activity->id;
479 CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
480 }
481 }
482
c72ba2be 483 /**
f9ec2da6
TO
484 * @param \Civi\ActionSchedule\MappingInterface $mapping
485 * @param \CRM_Core_DAO_ActionSchedule $actionSchedule
20f48505 486 *
c72ba2be
TO
487 * @return string
488 */
489 protected static function prepareMailingQuery($mapping, $actionSchedule) {
f9ec2da6
TO
490 $select = CRM_Utils_SQL_Select::from('civicrm_action_log reminder')
491 ->select("reminder.id as reminderID, reminder.contact_id as contactID, reminder.entity_table as entityTable, reminder.*, e.id AS entityID")
492 ->join('e', "!casMailingJoinType !casMappingEntity e ON !casEntityJoinExpr")
493 ->select("e.id as entityID, e.*")
494 ->where("reminder.action_schedule_id = #casActionScheduleId")
495 ->where("reminder.action_date_time IS NULL")
be2fb01f 496 ->param([
f9ec2da6
TO
497 'casActionScheduleId' => $actionSchedule->id,
498 'casMailingJoinType' => ($actionSchedule->limit_to == 0) ? 'LEFT JOIN' : 'INNER JOIN',
499 'casMappingId' => $mapping->getId(),
500 'casMappingEntity' => $mapping->getEntity(),
94042e58 501 'casEntityJoinExpr' => 'e.id = IF(reminder.entity_table = "civicrm_contact", reminder.contact_id, reminder.entity_id)',
be2fb01f 502 ]);
a1466c59
TO
503
504 if ($actionSchedule->limit_to == 0) {
a1466c59
TO
505 $select->where("e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact'");
506 }
c72ba2be 507
4162ab6f 508 \Civi::dispatcher()
f9ec2da6 509 ->dispatch(
bc2feeb1 510 'civi.actionSchedule.prepareMailingQuery',
f9ec2da6
TO
511 new \Civi\ActionSchedule\Event\MailingQueryEvent($actionSchedule, $mapping, $select)
512 );
c72ba2be 513
a1466c59 514 return $select->toSQL();
c72ba2be
TO
515 }
516
43ceab3f 517 /**
09c2328a 518 * @param \Civi\Token\TokenRow $tokenRow
d22bcd5b
TO
519 * @param CRM_Core_DAO_ActionSchedule $schedule
520 * @param int $toContactID
43ceab3f 521 * @throws CRM_Core_Exception
d22bcd5b
TO
522 * @return array
523 * List of error messages.
43ceab3f 524 */
d22bcd5b
TO
525 protected static function sendReminderSms($tokenRow, $schedule, $toContactID) {
526 $toPhoneNumber = self::pickSmsPhoneNumber($toContactID);
527 if (!$toPhoneNumber) {
be2fb01f 528 return ["sms_phone_missing" => "Couldn't find recipient's phone number."];
d22bcd5b
TO
529 }
530
51c566a3
SL
531 // dev/core#369 If an SMS provider is deleted then the relevant row in the action_schedule_table is set to NULL
532 // So we need to exclude them.
533 if (CRM_Utils_System::isNull($schedule->sms_provider_id)) {
7f38cf7f 534 return ["sms_provider_missing" => "SMS reminder cannot be sent because the SMS provider has been deleted."];
51c566a3
SL
535 }
536
43ceab3f
TO
537 $messageSubject = $tokenRow->render('subject');
538 $sms_body_text = $tokenRow->render('sms_body_text');
539
540 $session = CRM_Core_Session::singleton();
541 $userID = $session->get('userID') ? $session->get('userID') : $tokenRow->context['contactId'];
be2fb01f 542 $smsParams = [
43ceab3f
TO
543 'To' => $toPhoneNumber,
544 'provider_id' => $schedule->sms_provider_id,
545 'activity_subject' => $messageSubject,
be2fb01f 546 ];
3c49839d 547 $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS');
be2fb01f 548 $activityParams = [
43ceab3f
TO
549 'source_contact_id' => $userID,
550 'activity_type_id' => $activityTypeID,
551 'activity_date_time' => date('YmdHis'),
552 'subject' => $messageSubject,
553 'details' => $sms_body_text,
593dbb07 554 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
be2fb01f 555 ];
43ceab3f
TO
556
557 $activity = CRM_Activity_BAO_Activity::create($activityParams);
558
4a0e3fe7
SL
559 try {
560 CRM_Activity_BAO_Activity::sendSMSMessage($tokenRow->context['contactId'],
561 $sms_body_text,
562 $smsParams,
563 $activity->id,
564 $userID
565 );
566 }
567 catch (CRM_Core_Exception $e) {
568 return ["sms_send_error" => $e->getMessage()];
569 }
d22bcd5b 570
be2fb01f 571 return [];
43ceab3f
TO
572 }
573
574 /**
575 * @param CRM_Core_DAO_ActionSchedule $actionSchedule
20f48505 576 *
43ceab3f
TO
577 * @return string
578 * Ex: "Alice <alice@example.org>".
20f48505 579 * @throws \CRM_Core_Exception
43ceab3f
TO
580 */
581 protected static function pickFromEmail($actionSchedule) {
582 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
583 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
584 if ($actionSchedule->from_email) {
6ad53728 585 $fromEmailAddress = "\"$actionSchedule->from_name\" <$actionSchedule->from_email>";
43ceab3f
TO
586 return $fromEmailAddress;
587 }
588 return $fromEmailAddress;
589 }
590
591 /**
09c2328a 592 * @param \Civi\Token\TokenRow $tokenRow
d22bcd5b
TO
593 * @param CRM_Core_DAO_ActionSchedule $schedule
594 * @param int $toContactID
595 * @return array
596 * List of error messages.
43ceab3f 597 */
83b2b36b 598 protected static function sendReminderEmail($tokenRow, $schedule, $toContactID): array {
157e2097 599 $toEmail = CRM_Contact_BAO_Contact::getPrimaryEmail($toContactID, TRUE);
d22bcd5b 600 if (!$toEmail) {
be2fb01f 601 return ["email_missing" => "Couldn't find recipient's email address."];
d22bcd5b
TO
602 }
603
43ceab3f
TO
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);
608 }
609
610 // set up the parameters for CRM_Utils_Mail::send
be2fb01f 611 $mailParams = [
43ceab3f
TO
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,
be2fb01f 619 ];
43ceab3f 620
83b2b36b 621 if (!$body_html || $tokenRow->context['contact']['preferred_mail_format'] === 'Text' ||
622 $tokenRow->context['contact']['preferred_mail_format'] === 'Both'
43ceab3f
TO
623 ) {
624 // render the &amp; entities in text mode, so that the links work
625 $mailParams['text'] = str_replace('&amp;', '&', $body_text);
626 }
83b2b36b 627 if ($body_html && ($tokenRow->context['contact']['preferred_mail_format'] === 'HTML' ||
628 $tokenRow->context['contact']['preferred_mail_format'] === 'Both'
43ceab3f
TO
629 )
630 ) {
631 $mailParams['html'] = $body_html;
632 }
633 $result = CRM_Utils_Mail::send($mailParams);
83b2b36b 634 if (!$result) {
be2fb01f 635 return ['email_fail' => 'Failed to send message'];
d22bcd5b
TO
636 }
637
be2fb01f 638 return [];
43ceab3f
TO
639 }
640
641 /**
642 * @param CRM_Core_DAO_ActionSchedule $schedule
50a23755 643 * @param \Civi\ActionSchedule\Mapping $mapping
43ceab3f
TO
644 * @return \Civi\Token\TokenProcessor
645 */
50a23755 646 protected static function createTokenProcessor($schedule, $mapping) {
4162ab6f 647 $tp = new \Civi\Token\TokenProcessor(\Civi::dispatcher(), [
43ceab3f
TO
648 'controller' => __CLASS__,
649 'actionSchedule' => $schedule,
50a23755 650 'actionMapping' => $mapping,
43ceab3f 651 'smarty' => TRUE,
be2fb01f 652 ]);
43ceab3f
TO
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');
657 return $tp;
658 }
659
d22bcd5b 660 /**
54957108 661 * Pick SMS phone number.
662 *
663 * @param int $smsToContactId
664 *
665 * @return NULL|string
d22bcd5b
TO
666 */
667 protected static function pickSmsPhoneNumber($smsToContactId) {
be2fb01f 668 $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($smsToContactId, FALSE, 'Mobile', [
d22bcd5b
TO
669 'is_deceased' => 0,
670 'is_deleted' => 0,
671 'do_not_sms' => 0,
be2fb01f 672 ]);
d22bcd5b
TO
673 //to get primary mobile ph,if not get a first mobile phONE
674 if (!empty($toPhoneNumbers)) {
675 $toPhoneNumberDetails = reset($toPhoneNumbers);
9c1bc317 676 $toPhoneNumber = $toPhoneNumberDetails['phone'] ?? NULL;
d22bcd5b
TO
677 return $toPhoneNumber;
678 }
679 return NULL;
680 }
681
673c1c81
TO
682 /**
683 * Get the list of generic recipient types supported by all entities/mappings.
684 *
685 * @return array
686 * array(mixed $value => string $label).
687 */
20f48505 688 public static function getAdditionalRecipients(): array {
be2fb01f 689 return [
673c1c81
TO
690 'manual' => ts('Choose Recipient(s)'),
691 'group' => ts('Select Group'),
be2fb01f 692 ];
673c1c81
TO
693 }
694
6a488035 695}