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