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