3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
37 * This class contains functions for managing Scheduled Reminders
39 class CRM_Core_BAO_ActionSchedule
extends CRM_Core_DAO_ActionSchedule
{
42 * @param array $filters
43 * Filter by property (e.g. 'id').
45 * Array(scalar $id => Mapping $mapping).
47 public static function getMappings($filters = NULL) {
48 static $_action_mapping;
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();
57 if (empty($filters)) {
58 return $_action_mapping;
60 elseif (isset($filters['id'])) {
62 $filters['id'] => $_action_mapping[$filters['id']],
66 throw new CRM_Core_Exception("getMappings() called with unsupported filter: " . implode(', ', array_keys($filters)));
71 * Retrieve list of selections/drop downs for Scheduled Reminder form
77 * associated array of all the drop downs in the form
79 public static function getSelection($id = NULL) {
80 $mappings = CRM_Core_BAO_ActionSchedule
::getMappings();
82 $entityValueLabels = $entityStatusLabels = $dateFieldLabels = array();
83 $entityRecipientLabels = $entityRecipientNames = array();
89 foreach ($mappings as $mapping) {
90 /** @var \Civi\ActionSchedule\Mapping $mapping */
92 $mappingId = $mapping->getId();
93 $entityValueLabels[$mappingId] = $mapping->getValueLabels();
94 // Not sure why: everything *except* contact-dates have a $valueLabel.
95 if ($mapping->getId() !== CRM_Contact_ActionMapping
::CONTACT_MAPPING_ID
) {
96 $valueLabel = array('- ' . strtolower($mapping->getValueHeader()) . ' -');
97 $entityValueLabels[$mapping->getId()] = $valueLabel +
$entityValueLabels[$mapping->getId()];
100 if ($mapping->getId() == $id) {
101 $dateFieldLabels = $mapping->getDateFields();
102 $entityRecipientLabels = $mapping->getRecipientTypes();
103 $entityRecipientNames = array_combine(array_keys($entityRecipientLabels), array_keys($entityRecipientLabels));
106 $statusLabel = array('- ' . strtolower($mapping->getStatusHeader()) . ' -');
107 $entityStatusLabels[$mapping->getId()] = $entityValueLabels[$mapping->getId()];
108 foreach ($entityStatusLabels[$mapping->getId()] as $kkey => & $vval) {
109 $vval = $statusLabel +
$mapping->getStatusLabels($kkey);
113 $entityLabels = array_map(function ($v) {
114 return $v->getLabel();
116 $entityNames = array_map(function ($v) {
117 return $v->getEntity();
121 'sel1' => $entityLabels,
122 'sel2' => $entityValueLabels,
123 'sel3' => $entityStatusLabels,
124 'sel4' => $dateFieldLabels,
125 'sel5' => $entityRecipientLabels,
126 'entityMapping' => $entityNames,
127 'recipientMapping' => $entityRecipientNames,
132 * @param int $mappingId
133 * @param int $isLimit
137 public static function getSelection1($mappingId = NULL, $isLimit = NULL) {
138 $mappings = CRM_Core_BAO_ActionSchedule
::getMappings(array(
141 $dateFieldLabels = $entityRecipientLabels = array();
143 foreach ($mappings as $mapping) {
144 /** @var \Civi\ActionSchedule\Mapping $mapping */
145 $dateFieldLabels = $mapping->getDateFields();
146 $entityRecipientLabels = $mapping->getRecipientTypes(!$isLimit);
150 'sel4' => $dateFieldLabels,
151 'sel5' => $entityRecipientLabels,
152 'recipientMapping' => array_combine(array_keys($entityRecipientLabels), array_keys($entityRecipientLabels)),
157 * Retrieve list of Scheduled Reminders.
159 * @param bool $namesOnly
160 * Return simple list of names.
162 * @param \Civi\ActionSchedule\Mapping|NULL $filterMapping
163 * Filter by the schedule's mapping type.
164 * @param int $filterValue
165 * Filter by the schedule's entity_value.
168 * (reference) reminder list
170 public static function &getList($namesOnly = FALSE, $filterMapping = NULL, $filterValue = NULL) {
176 cas.entity_value as entityValueIds,
177 cas.entity_status as entityStatusIds,
178 cas.start_action_date as entityDate,
179 cas.start_action_offset,
180 cas.start_action_unit,
181 cas.start_action_condition,
186 FROM civicrm_action_schedule cas
188 $queryParams = array();
189 $where = " WHERE 1 ";
190 if ($filterMapping and $filterValue) {
191 $where .= " AND cas.entity_value = %1 AND cas.mapping_id = %2";
192 $queryParams[1] = array($filterValue, 'Integer');
193 $queryParams[2] = array($filterMapping->getId(), 'Integer');
195 $where .= " AND cas.used_for IS NULL";
197 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
198 while ($dao->fetch()) {
199 /** @var Civi\ActionSchedule\Mapping $filterMapping */
200 $filterMapping = CRM_Utils_Array
::first(self
::getMappings(array(
201 'id' => $dao->mapping_id
,
203 $list[$dao->id
]['id'] = $dao->id
;
204 $list[$dao->id
]['title'] = $dao->title
;
205 $list[$dao->id
]['start_action_offset'] = $dao->start_action_offset
;
206 $list[$dao->id
]['start_action_unit'] = $dao->start_action_unit
;
207 $list[$dao->id
]['start_action_condition'] = $dao->start_action_condition
;
208 $list[$dao->id
]['entityDate'] = ucwords(str_replace('_', ' ', $dao->entityDate
));
209 $list[$dao->id
]['absolute_date'] = $dao->absolute_date
;
210 $list[$dao->id
]['entity'] = $filterMapping->getLabel();
211 $list[$dao->id
]['value'] = implode(', ', CRM_Utils_Array
::subset(
212 $filterMapping->getValueLabels(),
213 explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityValueIds
)
215 $list[$dao->id
]['status'] = implode(', ', CRM_Utils_Array
::subset(
216 $filterMapping->getStatusLabels($dao->entityValueIds
),
217 explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $dao->entityStatusIds
)
219 $list[$dao->id
]['is_repeat'] = $dao->is_repeat
;
220 $list[$dao->id
]['is_active'] = $dao->is_active
;
227 * Add the schedules reminders in the db.
229 * @param array $params
230 * (reference ) an assoc array of name/value pairs.
234 * @return CRM_Core_DAO_ActionSchedule
236 public static function add(&$params, $ids = array()) {
237 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
238 $actionSchedule->copyValues($params);
240 return $actionSchedule->save();
244 * Retrieve DB object based on input parameters.
246 * It also stores all the retrieved values in the default array.
248 * @param array $params
249 * (reference ) an assoc array of name/value pairs.
250 * @param array $values
251 * (reference ) an assoc array to hold the flattened values.
253 * @return CRM_Core_DAO_ActionSchedule|null
254 * object on success, null otherwise
256 public static function retrieve(&$params, &$values) {
257 if (empty($params)) {
260 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
262 $actionSchedule->copyValues($params);
264 if ($actionSchedule->find(TRUE)) {
265 $ids['actionSchedule'] = $actionSchedule->id
;
267 CRM_Core_DAO
::storeValues($actionSchedule, $values);
269 return $actionSchedule;
278 * ID of the Reminder to be deleted.
281 public static function del($id) {
283 $dao = new CRM_Core_DAO_ActionSchedule();
285 if ($dao->find(TRUE)) {
290 CRM_Core_Error
::fatal(ts('Invalid value passed to delete function.'));
294 * Update the is_active flag in the db.
297 * Id of the database record.
298 * @param bool $is_active
299 * Value we want to set the is_active field.
302 * DAO object on success, null otherwise
304 public static function setIsActive($id, $is_active) {
305 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
309 * @param int $mappingID
312 * @throws CRM_Core_Exception
314 public static function sendMailings($mappingID, $now) {
315 $mapping = CRM_Utils_Array
::first(self
::getMappings(array(
319 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
320 $actionSchedule->mapping_id
= $mappingID;
321 $actionSchedule->is_active
= 1;
322 $actionSchedule->find(FALSE);
324 while ($actionSchedule->fetch()) {
325 $query = CRM_Core_BAO_ActionSchedule
::prepareMailingQuery($mapping, $actionSchedule);
326 $dao = CRM_Core_DAO
::executeQuery($query,
327 array(1 => array($actionSchedule->id
, 'Integer'))
330 $multilingual = CRM_Core_I18n
::isMultilingual();
331 while ($dao->fetch()) {
332 // switch language if necessary
334 $preferred_language = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $dao->contactID
, 'preferred_language');
335 CRM_Core_BAO_ActionSchedule
::setCommunicationLanguage($actionSchedule->communication_language
, $preferred_language);
340 $tokenProcessor = self
::createTokenProcessor($actionSchedule, $mapping);
341 $tokenProcessor->addRow()
342 ->context('contactId', $dao->contactID
)
343 ->context('actionSearchResult', (object) $dao->toArray());
344 foreach ($tokenProcessor->evaluate()->getRows() as $tokenRow) {
345 if ($actionSchedule->mode
== 'SMS' or $actionSchedule->mode
== 'User_Preference') {
346 CRM_Utils_Array
::extend($errors, self
::sendReminderSms($tokenRow, $actionSchedule, $dao->contactID
));
349 if ($actionSchedule->mode
== 'Email' or $actionSchedule->mode
== 'User_Preference') {
350 CRM_Utils_Array
::extend($errors, self
::sendReminderEmail($tokenRow, $actionSchedule, $dao->contactID
));
354 catch (\Civi\Token\TokenException
$e) {
355 $errors['token_exception'] = $e->getMessage();
358 // update action log record
360 'id' => $dao->reminderID
,
361 'is_error' => !empty($errors),
362 'message' => empty($errors) ?
"null" : implode(' ', $errors),
363 'action_date_time' => $now,
365 CRM_Core_BAO_ActionLog
::create($logParams);
367 // insert activity log record if needed
368 if ($actionSchedule->record_activity
&& empty($errors)) {
369 $caseID = empty($dao->case_id
) ?
NULL : $dao->case_id
;
370 CRM_Core_BAO_ActionSchedule
::createMailingActivity($actionSchedule, $mapping, $dao->contactID
, $dao->entityID
, $caseID);
379 * @param int $mappingID
381 * @param array $params
383 * @throws API_Exception
385 public static function buildRecipientContacts($mappingID, $now, $params = array()) {
386 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
387 $actionSchedule->mapping_id
= $mappingID;
388 $actionSchedule->is_active
= 1;
389 if (!empty($params)) {
390 _civicrm_api3_dao_set_filter($actionSchedule, $params, FALSE);
392 $actionSchedule->find();
394 while ($actionSchedule->fetch()) {
395 /** @var \Civi\ActionSchedule\Mapping $mapping */
396 $mapping = CRM_Utils_Array
::first(self
::getMappings(array(
399 $builder = new \Civi\ActionSchedule\
RecipientBuilder($now, $actionSchedule, $mapping);
406 * @param array $params
410 public static function processQueue($now = NULL, $params = array()) {
411 $now = $now ? CRM_Utils_Time
::setTime($now) : CRM_Utils_Time
::getTime();
413 $mappings = CRM_Core_BAO_ActionSchedule
::getMappings();
414 foreach ($mappings as $mappingID => $mapping) {
415 CRM_Core_BAO_ActionSchedule
::buildRecipientContacts($mappingID, $now, $params);
416 CRM_Core_BAO_ActionSchedule
::sendMailings($mappingID, $now);
421 'messages' => ts('Sent all scheduled reminders successfully'),
428 * @param int $mappingID
430 * @return null|string
432 public static function isConfigured($id, $mappingID) {
433 $queryString = "SELECT count(id) FROM civicrm_action_schedule
434 WHERE mapping_id = %1 AND
438 1 => array($mappingID, 'Integer'),
439 2 => array($id, 'Integer'),
441 return CRM_Core_DAO
::singleValueQuery($queryString, $params);
445 * @param int $mappingID
446 * @param $recipientType
450 public static function getRecipientListing($mappingID, $recipientType) {
455 /** @var \Civi\ActionSchedule\Mapping $mapping */
456 $mapping = CRM_Utils_Array
::first(CRM_Core_BAO_ActionSchedule
::getMappings(array(
459 return $mapping->getRecipientListing($recipientType);
463 * @param $communication_language
464 * @param $preferred_language
466 public static function setCommunicationLanguage($communication_language, $preferred_language) {
467 $config = CRM_Core_Config
::singleton();
468 $language = $config->lcMessages
;
470 // prepare the language for the email
471 if ($communication_language == CRM_Core_I18n
::AUTO
) {
472 if (!empty($preferred_language)) {
473 $language = $preferred_language;
477 $language = $communication_language;
480 // language not in the existing language, use default
481 $languages = CRM_Core_I18n
::languages(TRUE);
482 if (!in_array($language, $languages)) {
483 $language = $config->lcMessages
;
486 // change the language
487 $i18n = CRM_Core_I18n
::singleton();
488 $i18n->setLanguage($language);
492 * Save a record about the delivery of a reminder email.
494 * WISHLIST: Instead of saving $actionSchedule->body_html, call this immediately after
495 * sending the message and pass in the fully rendered text of the message.
497 * @param CRM_Core_DAO_ActionSchedule $actionSchedule
498 * @param Civi\ActionSchedule\Mapping $mapping
499 * @param int $contactID
500 * @param int $entityID
501 * @param int|NULL $caseID
502 * @throws CRM_Core_Exception
504 protected static function createMailingActivity($actionSchedule, $mapping, $contactID, $entityID, $caseID) {
505 $session = CRM_Core_Session
::singleton();
507 if ($mapping->getEntity() == 'civicrm_membership') {
509 = CRM_Core_OptionGroup
::getValue('activity_type', 'Membership Renewal Reminder', 'name');
513 = CRM_Core_OptionGroup
::getValue('activity_type', 'Reminder Sent', 'name');
516 $activityParams = array(
517 'subject' => $actionSchedule->title
,
518 'details' => $actionSchedule->body_html
,
519 'source_contact_id' => $session->get('userID') ?
$session->get('userID') : $contactID,
520 'target_contact_id' => $contactID,
521 'activity_date_time' => CRM_Utils_Time
::getTime('YmdHis'),
522 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
523 'activity_type_id' => $activityTypeID,
524 'source_record_id' => $entityID,
526 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
528 //file reminder on case if source activity is a case activity
529 if (!empty($caseID)) {
530 $caseActivityParams = array();
531 $caseActivityParams['case_id'] = $caseID;
532 $caseActivityParams['activity_id'] = $activity->id
;
533 CRM_Case_BAO_Case
::processCaseActivity($caseActivityParams);
538 * @param \Civi\ActionSchedule\MappingInterface $mapping
539 * @param \CRM_Core_DAO_ActionSchedule $actionSchedule
542 protected static function prepareMailingQuery($mapping, $actionSchedule) {
543 $select = CRM_Utils_SQL_Select
::from('civicrm_action_log reminder')
544 ->select("reminder.id as reminderID, reminder.contact_id as contactID, reminder.entity_table as entityTable, reminder.*, e.id AS entityID")
545 ->join('e', "!casMailingJoinType !casMappingEntity e ON !casEntityJoinExpr")
546 ->select("e.id as entityID, e.*")
547 ->where("reminder.action_schedule_id = #casActionScheduleId")
548 ->where("reminder.action_date_time IS NULL")
550 'casActionScheduleId' => $actionSchedule->id
,
551 'casMailingJoinType' => ($actionSchedule->limit_to
== 0) ?
'LEFT JOIN' : 'INNER JOIN',
552 'casMappingId' => $mapping->getId(),
553 'casMappingEntity' => $mapping->getEntity(),
554 'casEntityJoinExpr' => 'e.id = reminder.entity_id',
557 if ($actionSchedule->limit_to
== 0) {
558 $select->where("e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact'");
561 \Civi\Core\Container
::singleton()->get('dispatcher')
563 \Civi\ActionSchedule\Events
::MAILING_QUERY
,
564 new \Civi\ActionSchedule\Event\
MailingQueryEvent($actionSchedule, $mapping, $select)
567 return $select->toSQL();
571 * @param TokenRow $tokenRow
572 * @param CRM_Core_DAO_ActionSchedule $schedule
573 * @param int $toContactID
574 * @throws CRM_Core_Exception
576 * List of error messages.
578 protected static function sendReminderSms($tokenRow, $schedule, $toContactID) {
579 $toPhoneNumber = self
::pickSmsPhoneNumber($toContactID);
580 if (!$toPhoneNumber) {
581 return array("sms_phone_missing" => "Couldn't find recipient's phone number.");
584 $messageSubject = $tokenRow->render('subject');
585 $sms_body_text = $tokenRow->render('sms_body_text');
587 $session = CRM_Core_Session
::singleton();
588 $userID = $session->get('userID') ?
$session->get('userID') : $tokenRow->context
['contactId'];
590 'To' => $toPhoneNumber,
591 'provider_id' => $schedule->sms_provider_id
,
592 'activity_subject' => $messageSubject,
594 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
598 $activityParams = array(
599 'source_contact_id' => $userID,
600 'activity_type_id' => $activityTypeID,
601 'activity_date_time' => date('YmdHis'),
602 'subject' => $messageSubject,
603 'details' => $sms_body_text,
604 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
607 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
609 CRM_Activity_BAO_Activity
::sendSMSMessage($tokenRow->context
['contactId'],
620 * @param CRM_Core_DAO_ActionSchedule $actionSchedule
622 * Ex: "Alice <alice@example.org>".
624 protected static function pickFromEmail($actionSchedule) {
625 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
626 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
627 if ($actionSchedule->from_email
) {
628 $fromEmailAddress = "$actionSchedule->from_name <$actionSchedule->from_email>";
629 return $fromEmailAddress;
631 return $fromEmailAddress;
635 * @param TokenRow $tokenRow
636 * @param CRM_Core_DAO_ActionSchedule $schedule
637 * @param int $toContactID
639 * List of error messages.
641 protected static function sendReminderEmail($tokenRow, $schedule, $toContactID) {
642 $toEmail = CRM_Contact_BAO_Contact
::getPrimaryEmail($toContactID);
644 return array("email_missing" => "Couldn't find recipient's email address.");
647 $body_text = $tokenRow->render('body_text');
648 $body_html = $tokenRow->render('body_html');
649 if (!$schedule->body_text
) {
650 $body_text = CRM_Utils_String
::htmlToText($body_html);
653 // set up the parameters for CRM_Utils_Mail::send
655 'groupName' => 'Scheduled Reminder Sender',
656 'from' => self
::pickFromEmail($schedule),
657 'toName' => $tokenRow->context
['contact']['display_name'],
658 'toEmail' => $toEmail,
659 'subject' => $tokenRow->render('subject'),
660 'entity' => 'action_schedule',
661 'entity_id' => $schedule->id
,
664 if (!$body_html ||
$tokenRow->context
['contact']['preferred_mail_format'] == 'Text' ||
665 $tokenRow->context
['contact']['preferred_mail_format'] == 'Both'
667 // render the & entities in text mode, so that the links work
668 $mailParams['text'] = str_replace('&', '&', $body_text);
670 if ($body_html && ($tokenRow->context
['contact']['preferred_mail_format'] == 'HTML' ||
671 $tokenRow->context
['contact']['preferred_mail_format'] == 'Both'
674 $mailParams['html'] = $body_html;
676 $result = CRM_Utils_Mail
::send($mailParams);
677 if (!$result ||
is_a($result, 'PEAR_Error')) {
678 return array('email_fail' => 'Failed to send message');
685 * @param CRM_Core_DAO_ActionSchedule $schedule
686 * @param \Civi\ActionSchedule\Mapping $mapping
687 * @return \Civi\Token\TokenProcessor
689 protected static function createTokenProcessor($schedule, $mapping) {
690 $tp = new \Civi\Token\
TokenProcessor(\Civi\Core\Container
::singleton()->get('dispatcher'), array(
691 'controller' => __CLASS__
,
692 'actionSchedule' => $schedule,
693 'actionMapping' => $mapping,
696 $tp->addMessage('body_text', $schedule->body_text
, 'text/plain');
697 $tp->addMessage('body_html', $schedule->body_html
, 'text/html');
698 $tp->addMessage('sms_body_text', $schedule->sms_body_text
, 'text/plain');
699 $tp->addMessage('subject', $schedule->subject
, 'text/plain');
705 * @return string|NULL
707 protected static function pickSmsPhoneNumber($smsToContactId) {
708 $toPhoneNumbers = CRM_Core_BAO_Phone
::allPhones($smsToContactId, FALSE, 'Mobile', array(
713 //to get primary mobile ph,if not get a first mobile phONE
714 if (!empty($toPhoneNumbers)) {
715 $toPhoneNumberDetails = reset($toPhoneNumbers);
716 $toPhoneNumber = CRM_Utils_Array
::value('phone', $toPhoneNumberDetails);
717 return $toPhoneNumber;