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