Merge pull request #21965 from civicrm/5.43
[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 215 * @param int $id
67d870c5 216 * @deprecated
ac15829d 217 * @throws CRM_Core_Exception
6a488035 218 */
00be9182 219 public static function del($id) {
67d870c5 220 self::deleteRecord(['id' => $id]);
6a488035
TO
221 }
222
223 /**
fe482240 224 * Update the is_active flag in the db.
6a488035 225 *
6a0b768e
TO
226 * @param int $id
227 * Id of the database record.
228 * @param bool $is_active
229 * Value we want to set the is_active field.
6a488035 230 *
8a4fede3 231 * @return bool
232 * true if we found and updated the object, else false
6a488035 233 */
00be9182 234 public static function setIsActive($id, $is_active) {
6a488035
TO
235 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
236 }
237
b5c2afd0 238 /**
100fef9d 239 * @param int $mappingID
b5c2afd0
EM
240 * @param $now
241 *
242 * @throws CRM_Core_Exception
243 */
00be9182 244 public static function sendMailings($mappingID, $now) {
be2fb01f 245 $mapping = CRM_Utils_Array::first(self::getMappings([
50a23755 246 'id' => $mappingID,
be2fb01f 247 ]));
6a488035
TO
248
249 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
250 $actionSchedule->mapping_id = $mappingID;
251 $actionSchedule->is_active = 1;
252 $actionSchedule->find(FALSE);
253
6a488035 254 while ($actionSchedule->fetch()) {
5b16d8b6 255 $query = CRM_Core_BAO_ActionSchedule::prepareMailingQuery($mapping, $actionSchedule);
6a488035 256 $dao = CRM_Core_DAO::executeQuery($query,
be2fb01f 257 [1 => [$actionSchedule->id, 'Integer']]
6a488035
TO
258 );
259
07844ccf 260 $multilingual = CRM_Core_I18n::isMultilingual();
c06f174f 261 $tokenProcessor = self::createTokenProcessor($actionSchedule, $mapping);
6a488035 262 while ($dao->fetch()) {
39eb69ec
TO
263 $row = $tokenProcessor->addRow()
264 ->context('contactId', $dao->contactID)
265 ->context('actionSearchResult', (object) $dao->toArray());
f14b9b1b 266
39eb69ec
TO
267 // switch language if necessary
268 if ($multilingual) {
269 $preferred_language = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $dao->contactID, 'preferred_language');
270 $row->context('locale', CRM_Core_BAO_ActionSchedule::pickLocale($actionSchedule->communication_language, $preferred_language));
271 }
3b191d7d
TO
272
273 foreach ($dao->toArray() as $key => $value) {
274 if (preg_match('/^tokenContext_(.*)/', $key, $m)) {
275 if (!in_array($m[1], $tokenProcessor->context['schema'])) {
276 $tokenProcessor->context['schema'][] = $m[1];
277 }
278 $row->context($m[1], $value);
279 }
280 }
c06f174f 281 }
7c0d7335 282
c06f174f
TO
283 $tokenProcessor->evaluate();
284 foreach ($tokenProcessor->getRows() as $tokenRow) {
285 $dao = $tokenRow->context['actionSearchResult'];
286 $errors = [];
6a488035 287
c06f174f
TO
288 // It's possible, eg, that sendReminderEmail fires Hook::alterMailParams() and that some listener use ts().
289 $swapLocale = empty($row->context['locale']) ? NULL : \CRM_Utils_AutoClean::swapLocale($row->context['locale']);
7c0d7335 290
c06f174f
TO
291 if ($actionSchedule->mode === 'SMS' || $actionSchedule->mode === 'User_Preference') {
292 CRM_Utils_Array::extend($errors, self::sendReminderSms($tokenRow, $actionSchedule, $dao->contactID));
293 }
39eb69ec 294
c06f174f
TO
295 if ($actionSchedule->mode === 'Email' || $actionSchedule->mode === 'User_Preference') {
296 CRM_Utils_Array::extend($errors, self::sendReminderEmail($tokenRow, $actionSchedule, $dao->contactID));
297 }
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);
6a488035
TO
302 }
303
c06f174f
TO
304 unset($swapLocale);
305
6a488035 306 // update action log record
be2fb01f 307 $logParams = [
6a488035 308 'id' => $dao->reminderID,
d22bcd5b
TO
309 'is_error' => !empty($errors),
310 'message' => empty($errors) ? "null" : implode(' ', $errors),
6a488035 311 'action_date_time' => $now,
be2fb01f 312 ];
6a488035 313 CRM_Core_BAO_ActionLog::create($logParams);
6a488035
TO
314 }
315
6a488035
TO
316 }
317 }
318
b5c2afd0 319 /**
2e9914a0 320 * Build a list of the contacts to send to.
321 *
322 * @param string $mappingID
323 * Value from the mapping_id field in the civicrm_action_schedule able. It might be a string like
324 * 'contribpage' for an older class like CRM_Contribute_ActionMapping_ByPage of for ones following
325 * more recent patterns, an integer.
326 * @param string $now
b5c2afd0
EM
327 * @param array $params
328 *
329 * @throws API_Exception
2e9914a0 330 * @throws \CRM_Core_Exception
b5c2afd0 331 */
2e9914a0 332 public static function buildRecipientContacts(string $mappingID, $now, $params = []) {
6a488035 333 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
2e9914a0 334
6a488035
TO
335 $actionSchedule->mapping_id = $mappingID;
336 $actionSchedule->is_active = 1;
22e263ad 337 if (!empty($params)) {
244bbdd8 338 _civicrm_api3_dao_set_filter($actionSchedule, $params, FALSE);
73f3e293 339 }
6a488035
TO
340 $actionSchedule->find();
341
342 while ($actionSchedule->fetch()) {
77e16391 343 /** @var \Civi\ActionSchedule\Mapping $mapping */
be2fb01f 344 $mapping = CRM_Utils_Array::first(self::getMappings([
50a23755 345 'id' => $mappingID,
be2fb01f 346 ]));
c09bacfd
TO
347 $builder = new \Civi\ActionSchedule\RecipientBuilder($now, $actionSchedule, $mapping);
348 $builder->build();
6a488035
TO
349 }
350 }
351
b5c2afd0 352 /**
2e9914a0 353 * Main processing callback for sending out scheduled reminders.
354 *
355 * @param string $now
b5c2afd0
EM
356 * @param array $params
357 *
2e9914a0 358 * @throws \API_Exception
359 * @throws \CRM_Core_Exception
b5c2afd0 360 */
87fa0491 361 public static function processQueue($now = NULL, $params = []): void {
6a488035
TO
362 $now = $now ? CRM_Utils_Time::setTime($now) : CRM_Utils_Time::getTime();
363
50a23755 364 $mappings = CRM_Core_BAO_ActionSchedule::getMappings();
6a488035 365 foreach ($mappings as $mappingID => $mapping) {
2e9914a0 366 CRM_Core_BAO_ActionSchedule::buildRecipientContacts((string) $mappingID, $now, $params);
5b16d8b6 367 CRM_Core_BAO_ActionSchedule::sendMailings($mappingID, $now);
6a488035 368 }
6a488035
TO
369 }
370
9a4df24c 371 /**
100fef9d
CW
372 * @param int $id
373 * @param int $mappingID
9a4df24c
EM
374 *
375 * @return null|string
376 */
00be9182 377 public static function isConfigured($id, $mappingID) {
6a488035
TO
378 $queryString = "SELECT count(id) FROM civicrm_action_schedule
379 WHERE mapping_id = %1 AND
380 entity_value = %2";
381
be2fb01f
CW
382 $params = [
383 1 => [$mappingID, 'String'],
384 2 => [$id, 'Integer'],
385 ];
6a488035
TO
386 return CRM_Core_DAO::singleValueQuery($queryString, $params);
387 }
388
b5c2afd0 389 /**
100fef9d 390 * @param int $mappingID
b5c2afd0
EM
391 * @param $recipientType
392 *
393 * @return array
394 */
00be9182 395 public static function getRecipientListing($mappingID, $recipientType) {
77e16391 396 if (!$mappingID) {
be2fb01f 397 return [];
6a488035
TO
398 }
399
77e16391 400 /** @var \Civi\ActionSchedule\Mapping $mapping */
be2fb01f 401 $mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings([
50a23755 402 'id' => $mappingID,
be2fb01f 403 ]));
77e16391 404 return $mapping->getRecipientListing($recipientType);
6a488035 405 }
96025800 406
07844ccf 407 /**
389aeb70
TO
408 * @param string|null $communication_language
409 * @param string|null $preferred_language
410 * @return string
07844ccf 411 */
389aeb70 412 public static function pickLocale($communication_language, $preferred_language) {
c86241f4 413 $currentLocale = CRM_Core_I18n::getLocale();
8ea23016 414 $language = $currentLocale;
fadd4d37 415
07844ccf
SV
416 // prepare the language for the email
417 if ($communication_language == CRM_Core_I18n::AUTO) {
418 if (!empty($preferred_language)) {
419 $language = $preferred_language;
420 }
421 }
422 else {
423 $language = $communication_language;
424 }
425
426 // language not in the existing language, use default
273f9849 427 $languages = CRM_Core_I18n::languages(TRUE);
8ea23016
SV
428 if (!array_key_exists($language, $languages)) {
429 $language = $currentLocale;
07844ccf
SV
430 }
431
432 // change the language
389aeb70 433 return $language;
07844ccf
SV
434 }
435
c72ba2be
TO
436 /**
437 * Save a record about the delivery of a reminder email.
438 *
439 * WISHLIST: Instead of saving $actionSchedule->body_html, call this immediately after
440 * sending the message and pass in the fully rendered text of the message.
441 *
d19632b1 442 * @param object $tokenRow
50a23755 443 * @param Civi\ActionSchedule\Mapping $mapping
c72ba2be
TO
444 * @param int $contactID
445 * @param int $entityID
e97c66ff 446 * @param int|null $caseID
c72ba2be
TO
447 * @throws CRM_Core_Exception
448 */
d19632b1 449 protected static function createMailingActivity($tokenRow, $mapping, $contactID, $entityID, $caseID) {
c72ba2be
TO
450 $session = CRM_Core_Session::singleton();
451
9e1bf145 452 if ($mapping->getEntity() == 'civicrm_membership') {
d66c61b6 453 // @todo - not required with api
c72ba2be 454 $activityTypeID
d66c61b6 455 = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Membership Renewal Reminder');
c72ba2be
TO
456 }
457 else {
d66c61b6 458 // @todo - not required with api
c72ba2be 459 $activityTypeID
d66c61b6 460 = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Reminder Sent');
c72ba2be
TO
461 }
462
be2fb01f 463 $activityParams = [
d19632b1
JP
464 'subject' => $tokenRow->render('subject'),
465 'details' => $tokenRow->render('body_html'),
c72ba2be
TO
466 'source_contact_id' => $session->get('userID') ? $session->get('userID') : $contactID,
467 'target_contact_id' => $contactID,
d66c61b6 468 // @todo - not required with api
c72ba2be 469 'activity_date_time' => CRM_Utils_Time::getTime('YmdHis'),
d66c61b6 470 // @todo - not required with api
471 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
c72ba2be
TO
472 'activity_type_id' => $activityTypeID,
473 'source_record_id' => $entityID,
be2fb01f 474 ];
d66c61b6 475 // @todo use api, remove all the above wrangling
c72ba2be
TO
476 $activity = CRM_Activity_BAO_Activity::create($activityParams);
477
478 //file reminder on case if source activity is a case activity
479 if (!empty($caseID)) {
be2fb01f 480 $caseActivityParams = [];
c72ba2be
TO
481 $caseActivityParams['case_id'] = $caseID;
482 $caseActivityParams['activity_id'] = $activity->id;
483 CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
484 }
485 }
486
c72ba2be 487 /**
f9ec2da6
TO
488 * @param \Civi\ActionSchedule\MappingInterface $mapping
489 * @param \CRM_Core_DAO_ActionSchedule $actionSchedule
20f48505 490 *
c72ba2be
TO
491 * @return string
492 */
493 protected static function prepareMailingQuery($mapping, $actionSchedule) {
f9ec2da6
TO
494 $select = CRM_Utils_SQL_Select::from('civicrm_action_log reminder')
495 ->select("reminder.id as reminderID, reminder.contact_id as contactID, reminder.entity_table as entityTable, reminder.*, e.id AS entityID")
496 ->join('e', "!casMailingJoinType !casMappingEntity e ON !casEntityJoinExpr")
497 ->select("e.id as entityID, e.*")
498 ->where("reminder.action_schedule_id = #casActionScheduleId")
499 ->where("reminder.action_date_time IS NULL")
be2fb01f 500 ->param([
f9ec2da6
TO
501 'casActionScheduleId' => $actionSchedule->id,
502 'casMailingJoinType' => ($actionSchedule->limit_to == 0) ? 'LEFT JOIN' : 'INNER JOIN',
503 'casMappingId' => $mapping->getId(),
504 'casMappingEntity' => $mapping->getEntity(),
94042e58 505 'casEntityJoinExpr' => 'e.id = IF(reminder.entity_table = "civicrm_contact", reminder.contact_id, reminder.entity_id)',
be2fb01f 506 ]);
a1466c59
TO
507
508 if ($actionSchedule->limit_to == 0) {
a1466c59
TO
509 $select->where("e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact'");
510 }
c72ba2be 511
4162ab6f 512 \Civi::dispatcher()
f9ec2da6 513 ->dispatch(
bc2feeb1 514 'civi.actionSchedule.prepareMailingQuery',
f9ec2da6
TO
515 new \Civi\ActionSchedule\Event\MailingQueryEvent($actionSchedule, $mapping, $select)
516 );
c72ba2be 517
a1466c59 518 return $select->toSQL();
c72ba2be
TO
519 }
520
43ceab3f 521 /**
09c2328a 522 * @param \Civi\Token\TokenRow $tokenRow
d22bcd5b
TO
523 * @param CRM_Core_DAO_ActionSchedule $schedule
524 * @param int $toContactID
43ceab3f 525 * @throws CRM_Core_Exception
d22bcd5b
TO
526 * @return array
527 * List of error messages.
43ceab3f 528 */
d22bcd5b
TO
529 protected static function sendReminderSms($tokenRow, $schedule, $toContactID) {
530 $toPhoneNumber = self::pickSmsPhoneNumber($toContactID);
531 if (!$toPhoneNumber) {
be2fb01f 532 return ["sms_phone_missing" => "Couldn't find recipient's phone number."];
d22bcd5b
TO
533 }
534
51c566a3
SL
535 // dev/core#369 If an SMS provider is deleted then the relevant row in the action_schedule_table is set to NULL
536 // So we need to exclude them.
537 if (CRM_Utils_System::isNull($schedule->sms_provider_id)) {
7f38cf7f 538 return ["sms_provider_missing" => "SMS reminder cannot be sent because the SMS provider has been deleted."];
51c566a3
SL
539 }
540
43ceab3f
TO
541 $messageSubject = $tokenRow->render('subject');
542 $sms_body_text = $tokenRow->render('sms_body_text');
543
544 $session = CRM_Core_Session::singleton();
545 $userID = $session->get('userID') ? $session->get('userID') : $tokenRow->context['contactId'];
be2fb01f 546 $smsParams = [
43ceab3f
TO
547 'To' => $toPhoneNumber,
548 'provider_id' => $schedule->sms_provider_id,
549 'activity_subject' => $messageSubject,
be2fb01f 550 ];
3c49839d 551 $activityTypeID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'SMS');
be2fb01f 552 $activityParams = [
43ceab3f
TO
553 'source_contact_id' => $userID,
554 'activity_type_id' => $activityTypeID,
555 'activity_date_time' => date('YmdHis'),
556 'subject' => $messageSubject,
557 'details' => $sms_body_text,
593dbb07 558 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
be2fb01f 559 ];
43ceab3f
TO
560
561 $activity = CRM_Activity_BAO_Activity::create($activityParams);
562
4a0e3fe7
SL
563 try {
564 CRM_Activity_BAO_Activity::sendSMSMessage($tokenRow->context['contactId'],
565 $sms_body_text,
566 $smsParams,
567 $activity->id,
568 $userID
569 );
570 }
571 catch (CRM_Core_Exception $e) {
572 return ["sms_send_error" => $e->getMessage()];
573 }
d22bcd5b 574
be2fb01f 575 return [];
43ceab3f
TO
576 }
577
578 /**
579 * @param CRM_Core_DAO_ActionSchedule $actionSchedule
20f48505 580 *
43ceab3f
TO
581 * @return string
582 * Ex: "Alice <alice@example.org>".
20f48505 583 * @throws \CRM_Core_Exception
43ceab3f
TO
584 */
585 protected static function pickFromEmail($actionSchedule) {
586 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
587 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
588 if ($actionSchedule->from_email) {
6ad53728 589 $fromEmailAddress = "\"$actionSchedule->from_name\" <$actionSchedule->from_email>";
43ceab3f
TO
590 return $fromEmailAddress;
591 }
592 return $fromEmailAddress;
593 }
594
595 /**
09c2328a 596 * @param \Civi\Token\TokenRow $tokenRow
d22bcd5b
TO
597 * @param CRM_Core_DAO_ActionSchedule $schedule
598 * @param int $toContactID
599 * @return array
600 * List of error messages.
43ceab3f 601 */
83b2b36b 602 protected static function sendReminderEmail($tokenRow, $schedule, $toContactID): array {
157e2097 603 $toEmail = CRM_Contact_BAO_Contact::getPrimaryEmail($toContactID, TRUE);
d22bcd5b 604 if (!$toEmail) {
be2fb01f 605 return ["email_missing" => "Couldn't find recipient's email address."];
d22bcd5b
TO
606 }
607
43ceab3f
TO
608 $body_text = $tokenRow->render('body_text');
609 $body_html = $tokenRow->render('body_html');
610 if (!$schedule->body_text) {
611 $body_text = CRM_Utils_String::htmlToText($body_html);
612 }
613
614 // set up the parameters for CRM_Utils_Mail::send
be2fb01f 615 $mailParams = [
43ceab3f
TO
616 'groupName' => 'Scheduled Reminder Sender',
617 'from' => self::pickFromEmail($schedule),
bb193280 618 'toName' => $tokenRow->render('toName'),
43ceab3f
TO
619 'toEmail' => $toEmail,
620 'subject' => $tokenRow->render('subject'),
621 'entity' => 'action_schedule',
622 'entity_id' => $schedule->id,
be2fb01f 623 ];
43ceab3f 624
bb193280
EM
625 $preferredMailFormat = $tokenRow->render('preferred_mail_format');
626 if (!$body_html || $preferredMailFormat === 'Text' || $preferredMailFormat === 'Both'
43ceab3f
TO
627 ) {
628 // render the &amp; entities in text mode, so that the links work
629 $mailParams['text'] = str_replace('&amp;', '&', $body_text);
630 }
83b2b36b 631 if ($body_html && ($tokenRow->context['contact']['preferred_mail_format'] === 'HTML' ||
632 $tokenRow->context['contact']['preferred_mail_format'] === 'Both'
43ceab3f
TO
633 )
634 ) {
635 $mailParams['html'] = $body_html;
636 }
637 $result = CRM_Utils_Mail::send($mailParams);
83b2b36b 638 if (!$result) {
be2fb01f 639 return ['email_fail' => 'Failed to send message'];
d22bcd5b
TO
640 }
641
be2fb01f 642 return [];
43ceab3f
TO
643 }
644
645 /**
646 * @param CRM_Core_DAO_ActionSchedule $schedule
50a23755 647 * @param \Civi\ActionSchedule\Mapping $mapping
43ceab3f
TO
648 * @return \Civi\Token\TokenProcessor
649 */
50a23755 650 protected static function createTokenProcessor($schedule, $mapping) {
4162ab6f 651 $tp = new \Civi\Token\TokenProcessor(\Civi::dispatcher(), [
43ceab3f
TO
652 'controller' => __CLASS__,
653 'actionSchedule' => $schedule,
50a23755 654 'actionMapping' => $mapping,
43ceab3f 655 'smarty' => TRUE,
be2fb01f 656 ]);
43ceab3f
TO
657 $tp->addMessage('body_text', $schedule->body_text, 'text/plain');
658 $tp->addMessage('body_html', $schedule->body_html, 'text/html');
659 $tp->addMessage('sms_body_text', $schedule->sms_body_text, 'text/plain');
660 $tp->addMessage('subject', $schedule->subject, 'text/plain');
bb193280
EM
661 // These 2 are not 'real' tokens - but it tells the processor to load them.
662 $tp->addMessage('toName', '{contact.display_name}', 'text/plain');
663 $tp->addMessage('preferred_mail_format', '{contact.preferred_mail_format}', 'text/plain');
664
43ceab3f
TO
665 return $tp;
666 }
667
d22bcd5b 668 /**
54957108 669 * Pick SMS phone number.
670 *
671 * @param int $smsToContactId
672 *
673 * @return NULL|string
d22bcd5b
TO
674 */
675 protected static function pickSmsPhoneNumber($smsToContactId) {
be2fb01f 676 $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($smsToContactId, FALSE, 'Mobile', [
d22bcd5b
TO
677 'is_deceased' => 0,
678 'is_deleted' => 0,
679 'do_not_sms' => 0,
be2fb01f 680 ]);
d22bcd5b
TO
681 //to get primary mobile ph,if not get a first mobile phONE
682 if (!empty($toPhoneNumbers)) {
683 $toPhoneNumberDetails = reset($toPhoneNumbers);
9c1bc317 684 $toPhoneNumber = $toPhoneNumberDetails['phone'] ?? NULL;
d22bcd5b
TO
685 return $toPhoneNumber;
686 }
687 return NULL;
688 }
689
673c1c81
TO
690 /**
691 * Get the list of generic recipient types supported by all entities/mappings.
692 *
693 * @return array
694 * array(mixed $value => string $label).
695 */
20f48505 696 public static function getAdditionalRecipients(): array {
be2fb01f 697 return [
673c1c81
TO
698 'manual' => ts('Choose Recipient(s)'),
699 'group' => ts('Select Group'),
be2fb01f 700 ];
673c1c81
TO
701 }
702
6a488035 703}