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