CRM-16355 - cleanup, use of CRM_Core_I18n::language instead of a new function
[civicrm-core.git] / CRM / Core / BAO / ActionSchedule.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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 int $id
43 *
44 * @return array
45 */
46 public static function getMapping($id = NULL) {
47 static $_action_mapping;
48
49 if ($id && !is_null($_action_mapping) && isset($_action_mapping[$id])) {
50 return $_action_mapping[$id];
51 }
52
53 $dao = new CRM_Core_DAO_ActionMapping();
54 if ($id) {
55 $dao->id = $id;
56 }
57 $dao->find();
58
59 $mapping = array();
60 while ($dao->fetch()) {
61 $defaults = array();
62 CRM_Core_DAO::storeValues($dao, $defaults);
63 $mapping[$dao->id] = $defaults;
64 }
65 $_action_mapping = $mapping;
66
67 return $mapping;
68 }
69
70 /**
71 * Get all fields of the type Date.
72 */
73 public static function getDateFields() {
74 $allFields = CRM_Core_BAO_CustomField::getFields('');
75 $dateFields = array(
76 'birth_date' => ts('Birth Date'),
77 'created_date' => ts('Created Date'),
78 'modified_date' => ts('Modified Date'),
79 );
80 foreach ($allFields as $fieldID => $field) {
81 if ($field['data_type'] == 'Date') {
82 $dateFields["custom_$fieldID"] = $field['label'];
83 }
84 }
85 return $dateFields;
86 }
87
88 /**
89 * Retrieve list of selections/drop downs for Scheduled Reminder form
90 *
91 * @param bool $id
92 * Mapping id.
93 *
94 * @return array
95 * associated array of all the drop downs in the form
96 */
97 public static function getSelection($id = NULL) {
98 $mapping = self::getMapping();
99 $activityStatus = CRM_Core_PseudoConstant::activityStatus();
100 $activityType = CRM_Core_PseudoConstant::activityType(TRUE, TRUE);
101
102 $participantStatus = CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label');
103 $event = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
104 $eventType = CRM_Event_PseudoConstant::eventType();
105 $eventTemplate = CRM_Event_PseudoConstant::eventTemplates();
106 $autoRenew = CRM_Core_OptionGroup::values('auto_renew_options');
107 $membershipType = CRM_Member_PseudoConstant::membershipType();
108 $dateFieldParams = array('data_type' => 'Date');
109 $dateFields = self::getDateFields();
110 $contactOptions = CRM_Core_OptionGroup::values('contact_date_reminder_options');
111
112 asort($activityType);
113
114 $sel1 = $sel2 = $sel3 = $sel4 = $sel5 = array();
115 $options = array(
116 'manual' => ts('Choose Recipient(s)'),
117 'group' => ts('Select Group'),
118 );
119
120 $entityMapping = array();
121 $recipientMapping = array_combine(array_keys($options), array_keys($options));
122
123 if (!$id) {
124 $id = 1;
125 }
126
127 foreach ($mapping as $value) {
128 $entityValue = CRM_Utils_Array::value('entity_value', $value);
129 $entityStatus = CRM_Utils_Array::value('entity_status', $value);
130 $entityRecipient = CRM_Utils_Array::value('entity_recipient', $value);
131 $valueLabel = array('- ' . strtolower(CRM_Utils_Array::value('entity_value_label', $value)) . ' -');
132 $key = CRM_Utils_Array::value('id', $value);
133 $entityMapping[$key] = CRM_Utils_Array::value('entity', $value);
134
135 $sel1Val = NULL;
136 switch ($entityValue) {
137 case 'activity_type':
138 if ($value['entity'] == 'civicrm_activity') {
139 $sel1Val = ts('Activity');
140 }
141 $sel2[$key] = $valueLabel + $activityType;
142 break;
143
144 case 'event_type':
145 if ($value['entity'] == 'civicrm_participant') {
146 $sel1Val = ts('Event Type');
147 }
148 $sel2[$key] = $valueLabel + $eventType;
149 break;
150
151 case 'event_template':
152 if ($value['entity'] == 'civicrm_participant') {
153 $sel1Val = ts('Event Template');
154 }
155 $sel2[$key] = $valueLabel + $eventTemplate;
156 break;
157
158 case 'civicrm_event':
159 if ($value['entity'] == 'civicrm_participant') {
160 $sel1Val = ts('Event Name');
161 }
162 $sel2[$key] = $valueLabel + $event;
163 break;
164
165 case 'civicrm_membership_type':
166 if ($value['entity'] == 'civicrm_membership') {
167 $sel1Val = ts('Membership');
168 }
169 $sel2[$key] = $valueLabel + $membershipType;
170 break;
171
172 case 'civicrm_contact':
173 if ($value['entity'] == 'civicrm_contact') {
174 $sel1Val = ts('Contact');
175 }
176 $sel2[$key] = $dateFields;
177 break;
178 }
179 $sel1[$key] = $sel1Val;
180
181 if ($key == $id) {
182 if ($startDate = CRM_Utils_Array::value('entity_date_start', $value)) {
183 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
184 }
185 if ($endDate = CRM_Utils_Array::value('entity_date_end', $value)) {
186 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
187 }
188
189 switch ($entityRecipient) {
190 case 'activity_contacts':
191 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts');
192 $sel5[$entityRecipient] = $activityContacts + $options;
193 $recipientMapping += CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
194 break;
195
196 case 'event_contacts':
197 $eventContacts = CRM_Core_OptionGroup::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name');
198 $sel5[$entityRecipient] = $eventContacts + $options;
199 $recipientMapping += CRM_Core_OptionGroup::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
200 break;
201
202 case NULL:
203 $sel5[$entityRecipient] = $options;
204 break;
205 }
206 }
207 }
208 $sel3 = $sel2;
209
210 foreach ($mapping as $value) {
211 $entityStatus = CRM_Utils_Array::value('entity_status', $value);
212 $statusLabel = array('- ' . strtolower(CRM_Utils_Array::value('entity_status_label', $value)) . ' -');
213 $id = CRM_Utils_Array::value('id', $value);
214
215 switch ($entityStatus) {
216 case 'activity_status':
217 foreach ($sel3[$id] as $kkey => & $vval) {
218 $vval = $statusLabel + $activityStatus;
219 }
220 break;
221
222 case 'civicrm_participant_status_type':
223 foreach ($sel3[$id] as $kkey => & $vval) {
224 $vval = $statusLabel + $participantStatus;
225 }
226 break;
227
228 case 'auto_renew_options':
229 foreach ($sel3[$id] as $kkey => & $vval) {
230 $auto = 0;
231 if ($kkey) {
232 $auto = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $kkey, 'auto_renew');
233 }
234 if ($auto) {
235 $vval = $statusLabel + $autoRenew;
236 }
237 else {
238 $vval = $statusLabel;
239 }
240 }
241 break;
242
243 case 'contact_date_reminder_options':
244 foreach ($sel3[$id] as $kkey => & $vval) {
245 $vval = $contactOptions;
246 }
247 break;
248
249 case '':
250 $sel3[$id] = '';
251 break;
252
253 }
254 }
255 return array(
256 'sel1' => $sel1,
257 'sel2' => $sel2,
258 'sel3' => $sel3,
259 'sel4' => $sel4,
260 'sel5' => $sel5,
261 'entityMapping' => $entityMapping,
262 'recipientMapping' => $recipientMapping,
263 );
264 }
265
266 /**
267 * @param int $id
268 * @param int $isLimit
269 *
270 * @return array
271 */
272 public static function getSelection1($id = NULL, $isLimit = NULL) {
273 $mapping = self::getMapping($id);
274 $sel4 = $sel5 = array();
275 $options = array(
276 'manual' => ts('Choose Recipient(s)'),
277 'group' => ts('Select Group'),
278 );
279
280 $recipientMapping = array_combine(array_keys($options), array_keys($options));
281
282 foreach ($mapping as $value) {
283 $entityRecipient = CRM_Utils_Array::value('entity_recipient', $value);
284 $key = CRM_Utils_Array::value('id', $value);
285
286 if ($startDate = CRM_Utils_Array::value('entity_date_start', $value)) {
287 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
288 }
289 if ($endDate = CRM_Utils_Array::value('entity_date_end', $value)) {
290 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
291 }
292
293 switch ($entityRecipient) {
294 case 'activity_contacts':
295 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts');
296 $sel5[$id] = $activityContacts + $options;
297 $recipientMapping += CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
298 break;
299
300 case 'event_contacts':
301 //CRM-15536, don't provide participant_role option on choosing 'Also Include' for Event entity
302 if ($isLimit == 1) {
303 $options += CRM_Core_OptionGroup::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name');
304 }
305 $sel5[$id] = $options;
306 $recipientMapping += CRM_Core_OptionGroup::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
307 break;
308
309 case NULL:
310 $sel5[$id] = $options;
311 break;
312 }
313 }
314
315 return array(
316 'sel4' => $sel4,
317 'sel5' => $sel5[$id],
318 'recipientMapping' => $recipientMapping,
319 );
320 }
321
322 /**
323 * Retrieve list of Scheduled Reminders.
324 *
325 * @param bool $namesOnly
326 * Return simple list of names.
327 *
328 * @param null $entityValue
329 * @param int $id
330 *
331 * @return array
332 * (reference) reminder list
333 */
334 public static function &getList($namesOnly = FALSE, $entityValue = NULL, $id = NULL) {
335 $activity_type = CRM_Core_PseudoConstant::activityType(TRUE, TRUE);
336 $activity_status = CRM_Core_PseudoConstant::activityStatus();
337
338 $event_type = CRM_Event_PseudoConstant::eventType();
339 $civicrm_event = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
340 $civicrm_participant_status_type = CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label');
341 $event_template = CRM_Event_PseudoConstant::eventTemplates();
342 $civicrm_contact = self::getDateFields();
343
344 $auto_renew_options = CRM_Core_OptionGroup::values('auto_renew_options');
345 $contact_date_reminder_options = CRM_Core_OptionGroup::values('contact_date_reminder_options');
346 $civicrm_membership_type = CRM_Member_PseudoConstant::membershipType();
347
348 $entity = array(
349 'civicrm_activity' => 'Activity',
350 'civicrm_participant' => 'Event',
351 'civicrm_membership' => 'Member',
352 'civicrm_contact' => 'Contact',
353 );
354
355 $query = "
356 SELECT
357 title,
358 cam.entity,
359 cas.id as id,
360 cam.entity_value as entityValue,
361 cas.entity_value as entityValueIds,
362 cam.entity_status as entityStatus,
363 cas.entity_status as entityStatusIds,
364 cas.start_action_date as entityDate,
365 cas.start_action_offset,
366 cas.start_action_unit,
367 cas.start_action_condition,
368 cas.absolute_date,
369 is_repeat,
370 is_active
371
372 FROM civicrm_action_schedule cas
373 LEFT JOIN civicrm_action_mapping cam ON (cam.id = cas.mapping_id)
374 ";
375 $params = CRM_Core_DAO::$_nullArray;
376 $where = " WHERE 1 ";
377 if ($entityValue and $id) {
378 $where .= "
379 AND cas.entity_value = $id AND
380 cam.entity_value = '$entityValue'";
381
382 $params = array(
383 1 => array($id, 'Integer'),
384 2 => array($entityValue, 'String'),
385 );
386 }
387 $where .= " AND cas.used_for IS NULL";
388 $query .= $where;
389 $dao = CRM_Core_DAO::executeQuery($query);
390 while ($dao->fetch()) {
391 $list[$dao->id]['id'] = $dao->id;
392 $list[$dao->id]['title'] = $dao->title;
393 $list[$dao->id]['start_action_offset'] = $dao->start_action_offset;
394 $list[$dao->id]['start_action_unit'] = $dao->start_action_unit;
395 $list[$dao->id]['start_action_condition'] = $dao->start_action_condition;
396 $list[$dao->id]['entityDate'] = ucwords(str_replace('_', ' ', $dao->entityDate));
397 $list[$dao->id]['absolute_date'] = $dao->absolute_date;
398
399 $status = $dao->entityStatus;
400 $statusArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $dao->entityStatusIds);
401 foreach ($statusArray as & $s) {
402 $s = CRM_Utils_Array::value($s, $$status);
403 }
404 $statusIds = implode(', ', $statusArray);
405
406 $value = $dao->entityValue;
407 $valueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $dao->entityValueIds);
408 foreach ($valueArray as & $v) {
409 $v = CRM_Utils_Array::value($v, $$value);
410 }
411 $valueIds = implode(', ', $valueArray);
412 $list[$dao->id]['entity'] = $entity[$dao->entity];
413 $list[$dao->id]['value'] = $valueIds;
414 $list[$dao->id]['status'] = $statusIds;
415 $list[$dao->id]['is_repeat'] = $dao->is_repeat;
416 $list[$dao->id]['is_active'] = $dao->is_active;
417 }
418
419 return $list;
420 }
421
422 /**
423 * @param int $contactId
424 * @param $to
425 * @param int $scheduleID
426 * @param $from
427 * @param array $tokenParams
428 *
429 * @return bool|null
430 * @throws CRM_Core_Exception
431 */
432 public static function sendReminder($contactId, $to, $scheduleID, $from, $tokenParams) {
433 $email = $to['email'];
434 $phoneNumber = $to['phone'];
435 $schedule = new CRM_Core_DAO_ActionSchedule();
436 $schedule->id = $scheduleID;
437
438 $domain = CRM_Core_BAO_Domain::getDomain();
439 $result = NULL;
440 $hookTokens = array();
441
442 if ($schedule->find(TRUE)) {
443 $body_text = $schedule->body_text;
444 $body_html = $schedule->body_html;
445 $sms_body_text = $schedule->sms_body_text;
446 $body_subject = $schedule->subject;
447 if (!$body_text) {
448 $body_text = CRM_Utils_String::htmlToText($body_html);
449 }
450
451 $params = array(array('contact_id', '=', $contactId, 0, 0));
452 list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($params);
453
454 //CRM-4524
455 $contact = reset($contact);
456
457 if (!$contact || is_a($contact, 'CRM_Core_Error')) {
458 return NULL;
459 }
460
461 // merge activity tokens with contact array
462 $contact = array_merge($contact, $tokenParams);
463
464 //CRM-5734
465 CRM_Utils_Hook::tokenValues($contact, $contactId);
466
467 CRM_Utils_Hook::tokens($hookTokens);
468 $categories = array_keys($hookTokens);
469
470 $type = array('body_html' => 'html', 'body_text' => 'text', 'sms_body_text' => 'text');
471
472 foreach ($type as $bodyType => $value) {
473 $dummy_mail = new CRM_Mailing_BAO_Mailing();
474 if ($bodyType == 'sms_body_text') {
475 $dummy_mail->body_text = $$bodyType;
476 }
477 else {
478 $dummy_mail->$bodyType = $$bodyType;
479 }
480 $tokens = $dummy_mail->getTokens();
481
482 if ($$bodyType) {
483 CRM_Utils_Token::replaceGreetingTokens($$bodyType, NULL, $contact['contact_id']);
484 $$bodyType = CRM_Utils_Token::replaceDomainTokens($$bodyType, $domain, TRUE, $tokens[$value], TRUE);
485 $$bodyType = CRM_Utils_Token::replaceContactTokens($$bodyType, $contact, FALSE, $tokens[$value], FALSE, TRUE);
486 $$bodyType = CRM_Utils_Token::replaceComponentTokens($$bodyType, $contact, $tokens[$value], TRUE, FALSE);
487 $$bodyType = CRM_Utils_Token::replaceHookTokens($$bodyType, $contact, $categories, TRUE);
488 }
489 }
490 $html = $body_html;
491 $text = $body_text;
492 $sms_text = $sms_body_text;
493
494 $smarty = CRM_Core_Smarty::singleton();
495 foreach (array(
496 'text',
497 'html',
498 'sms_text',
499 ) as $elem) {
500 $$elem = $smarty->fetch("string:{$$elem}");
501 }
502
503 //@todo - this next section is a duplicate of function CRM_Utils_Token::getTokens
504 $matches = array();
505 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
506 $body_subject,
507 $matches,
508 PREG_PATTERN_ORDER
509 );
510
511 $subjectToken = NULL;
512 if ($matches[1]) {
513 foreach ($matches[1] as $token) {
514 list($type, $name) = preg_split('/\./', $token, 2);
515 if ($name) {
516 if (!isset($subjectToken[$type])) {
517 $subjectToken[$type] = array();
518 }
519 $subjectToken[$type][] = $name;
520 }
521 }
522 }
523
524 // @todo this (along with the copy-&-paste chunk above is a commonly repeated chunk of code & should be in a re-usable function
525 $messageSubject = CRM_Utils_Token::replaceContactTokens($body_subject, $contact, FALSE, $subjectToken);
526 $messageSubject = CRM_Utils_Token::replaceDomainTokens($messageSubject, $domain, TRUE, $subjectToken);
527 $messageSubject = CRM_Utils_Token::replaceComponentTokens($messageSubject, $contact, $subjectToken, TRUE);
528 $messageSubject = CRM_Utils_Token::replaceHookTokens($messageSubject, $contact, $categories, TRUE);
529
530 $messageSubject = $smarty->fetch("string:{$messageSubject}");
531
532 if ($schedule->mode == 'SMS' or $schedule->mode == 'User_Preference') {
533 $session = CRM_Core_Session::singleton();
534 $userID = $session->get('userID') ? $session->get('userID') : $contactId;
535 $smsParams = array(
536 'To' => $phoneNumber,
537 'provider_id' => $schedule->sms_provider_id,
538 'activity_subject' => $messageSubject,
539 );
540 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
541 'SMS',
542 'name'
543 );
544 $activityParams = array(
545 'source_contact_id' => $userID,
546 'activity_type_id' => $activityTypeID,
547 'activity_date_time' => date('YmdHis'),
548 'subject' => $messageSubject,
549 'details' => $sms_text,
550 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'),
551 );
552
553 $activity = CRM_Activity_BAO_Activity::create($activityParams);
554
555 CRM_Activity_BAO_Activity::sendSMSMessage($contactId,
556 $sms_text,
557 $smsParams,
558 $activity->id,
559 $userID
560 );
561 }
562
563 if ($schedule->mode == 'Email' or $schedule->mode == 'User_Preference') {
564 // set up the parameters for CRM_Utils_Mail::send
565 $mailParams = array(
566 'groupName' => 'Scheduled Reminder Sender',
567 'from' => $from,
568 'toName' => $contact['display_name'],
569 'toEmail' => $email,
570 'subject' => $messageSubject,
571 'entity' => 'action_schedule',
572 'entity_id' => $scheduleID,
573 );
574
575 if (!$html || $contact['preferred_mail_format'] == 'Text' ||
576 $contact['preferred_mail_format'] == 'Both'
577 ) {
578 // render the &amp; entities in text mode, so that the links work
579 $mailParams['text'] = str_replace('&amp;', '&', $text);
580 }
581 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
582 $contact['preferred_mail_format'] == 'Both'
583 )
584 ) {
585 $mailParams['html'] = $html;
586 }
587 $result = CRM_Utils_Mail::send($mailParams);
588 }
589 }
590 $schedule->free();
591
592 return $result;
593 }
594
595 /**
596 * Add the schedules reminders in the db.
597 *
598 * @param array $params
599 * (reference ) an assoc array of name/value pairs.
600 * @param array $ids
601 * Unused variable.
602 *
603 * @return CRM_Core_DAO_ActionSchedule
604 */
605 public static function add(&$params, $ids = array()) {
606 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
607 $actionSchedule->copyValues($params);
608
609 return $actionSchedule->save();
610 }
611
612 /**
613 * Retrieve DB object based on input parameters.
614 *
615 * It also stores all the retrieved values in the default array.
616 *
617 * @param array $params
618 * (reference ) an assoc array of name/value pairs.
619 * @param array $values
620 * (reference ) an assoc array to hold the flattened values.
621 *
622 * @return CRM_Core_DAO_ActionSchedule|null
623 * object on success, null otherwise
624 */
625 public static function retrieve(&$params, &$values) {
626 if (empty($params)) {
627 return NULL;
628 }
629 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
630
631 $actionSchedule->copyValues($params);
632
633 if ($actionSchedule->find(TRUE)) {
634 $ids['actionSchedule'] = $actionSchedule->id;
635
636 CRM_Core_DAO::storeValues($actionSchedule, $values);
637
638 return $actionSchedule;
639 }
640 return NULL;
641 }
642
643 /**
644 * Delete a Reminder.
645 *
646 * @param int $id
647 * ID of the Reminder to be deleted.
648 *
649 */
650 public static function del($id) {
651 if ($id) {
652 $dao = new CRM_Core_DAO_ActionSchedule();
653 $dao->id = $id;
654 if ($dao->find(TRUE)) {
655 $dao->delete();
656 return;
657 }
658 }
659 CRM_Core_Error::fatal(ts('Invalid value passed to delete function.'));
660 }
661
662 /**
663 * Update the is_active flag in the db.
664 *
665 * @param int $id
666 * Id of the database record.
667 * @param bool $is_active
668 * Value we want to set the is_active field.
669 *
670 * @return Object
671 * DAO object on success, null otherwise
672 */
673 public static function setIsActive($id, $is_active) {
674 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
675 }
676
677 /**
678 * @param int $mappingID
679 * @param $now
680 *
681 * @throws CRM_Core_Exception
682 */
683 public static function sendMailings($mappingID, $now) {
684 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
685 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
686
687 $mapping = new CRM_Core_DAO_ActionMapping();
688 $mapping->id = $mappingID;
689 $mapping->find(TRUE);
690
691 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
692 $actionSchedule->mapping_id = $mappingID;
693 $actionSchedule->is_active = 1;
694 $actionSchedule->find(FALSE);
695
696 $tokenFields = array();
697 $session = CRM_Core_Session::singleton();
698
699 while ($actionSchedule->fetch()) {
700 $extraSelect = $extraJoin = $extraWhere = $extraOn = '';
701
702 if ($actionSchedule->from_email) {
703 $fromEmailAddress = "$actionSchedule->from_name <$actionSchedule->from_email>";
704 }
705
706 $activityTypeID = FALSE;
707 $activityStatusID = FALSE;
708 if ($actionSchedule->record_activity) {
709 if ($mapping->entity == 'civicrm_membership') {
710 $activityTypeID
711 = CRM_Core_OptionGroup::getValue('activity_type', 'Membership Renewal Reminder', 'name');
712 }
713 else {
714 $activityTypeID
715 = CRM_Core_OptionGroup::getValue('activity_type', 'Reminder Sent', 'name');
716 }
717
718 $activityStatusID
719 = CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name');
720 }
721
722 if ($mapping->entity == 'civicrm_activity') {
723 $compInfo = CRM_Core_Component::getEnabledComponents();
724 $tokenEntity = 'activity';
725 $tokenFields = array('activity_id', 'activity_type', 'subject', 'details', 'activity_date_time');
726 $extraSelect = ', ov.label as activity_type, e.id as activity_id';
727 $extraJoin = "
728 INNER JOIN civicrm_option_group og ON og.name = 'activity_type'
729 INNER JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
730 $extraOn = ' AND e.is_current_revision = 1 AND e.is_deleted = 0 ';
731 if ($actionSchedule->limit_to == 0) {
732 $extraJoin = "
733 LEFT JOIN civicrm_option_group og ON og.name = 'activity_type'
734 LEFT JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
735 }
736
737 //join for caseId
738 // if CiviCase component is enabled
739 if (array_key_exists('CiviCase', $compInfo)) {
740 $extraSelect .= ", civicrm_case_activity.case_id as case_id";
741 $extraJoin .= "
742 LEFT JOIN `civicrm_case_activity` ON `e`.`id` = `civicrm_case_activity`.`activity_id`";
743 }
744 }
745
746 if ($mapping->entity == 'civicrm_participant') {
747 $tokenEntity = 'event';
748 $tokenFields = array(
749 'event_type',
750 'title',
751 'event_id',
752 'start_date',
753 'end_date',
754 'summary',
755 'description',
756 'location',
757 'info_url',
758 'registration_url',
759 'fee_amount',
760 'contact_email',
761 'contact_phone',
762 'balance',
763 );
764 $extraSelect = ', ov.label as event_type, ev.title, ev.id as event_id, ev.start_date, ev.end_date, ev.summary, ev.description, address.street_address, address.city, address.state_province_id, address.postal_code, email.email as contact_email, phone.phone as contact_phone ';
765
766 $extraJoin = "
767 INNER JOIN civicrm_event ev ON e.event_id = ev.id
768 INNER JOIN civicrm_option_group og ON og.name = 'event_type'
769 INNER JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
770 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
771 LEFT JOIN civicrm_address address ON address.id = lb.address_id
772 LEFT JOIN civicrm_email email ON email.id = lb.email_id
773 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
774 ";
775 if ($actionSchedule->limit_to == 0) {
776 $extraJoin = "
777 LEFT JOIN civicrm_event ev ON e.event_id = ev.id
778 LEFT JOIN civicrm_option_group og ON og.name = 'event_type'
779 LEFT JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
780 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
781 LEFT JOIN civicrm_address address ON address.id = lb.address_id
782 LEFT JOIN civicrm_email email ON email.id = lb.email_id
783 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
784 ";
785 }
786 }
787
788 if ($mapping->entity == 'civicrm_membership') {
789 $tokenEntity = 'membership';
790 $tokenFields = array('fee', 'id', 'join_date', 'start_date', 'end_date', 'status', 'type');
791 $extraSelect = ', mt.minimum_fee as fee, e.id as id , e.join_date, e.start_date, e.end_date, ms.name as status, mt.name as type';
792 $extraJoin = '
793 INNER JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
794 INNER JOIN civicrm_membership_status ms ON e.status_id = ms.id';
795
796 if ($actionSchedule->limit_to == 0) {
797 $extraJoin = '
798 LEFT JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
799 LEFT JOIN civicrm_membership_status ms ON e.status_id = ms.id';
800 }
801 }
802
803 if ($mapping->entity == 'civicrm_contact') {
804 $tokenEntity = 'contact';
805 //TODO: get full list somewhere!
806 $tokenFields = array('birth_date', 'last_name');
807 //TODO: is there anything to add here?
808 }
809
810 $entityJoinClause = "INNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
811 if ($actionSchedule->limit_to == 0) {
812 $entityJoinClause = "LEFT JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
813 $extraWhere .= " AND (e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact')";
814 }
815 $entityJoinClause .= $extraOn;
816
817
818 $query = "
819 SELECT reminder.id as reminderID, reminder.contact_id as contactID, reminder.entity_table as entityTable, reminder.*, e.id as entityID, e.* {$extraSelect}
820 FROM civicrm_action_log reminder
821 {$entityJoinClause}
822 {$extraJoin}
823 WHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL
824 {$extraWhere}";
825
826 $dao = CRM_Core_DAO::executeQuery($query,
827 array(1 => array($actionSchedule->id, 'Integer'))
828 );
829
830 $multilingual = CRM_Core_I18n::isMultilingual();
831 while ($dao->fetch()) {
832 // switch language if necessary
833 if ($multilingual) {
834 $cid = $dao->contactID;
835 $preferred_language = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'preferred_language');
836 CRM_Core_BAO_ActionSchedule::setCommunicationLanguage($actionSchedule->communication_language, $preferred_language);
837 }
838
839 $entityTokenParams = array();
840 foreach ($tokenFields as $field) {
841 if ($field == 'location') {
842 $loc = array();
843 $stateProvince = CRM_Core_PseudoConstant::stateProvince();
844 $loc['street_address'] = $dao->street_address;
845 $loc['city'] = $dao->city;
846 $loc['state_province'] = CRM_Utils_Array::value($dao->state_province_id, $stateProvince);
847 $loc['postal_code'] = $dao->postal_code;
848 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address::format($loc);
849 }
850 elseif ($field == 'info_url') {
851 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE);
852 }
853 elseif ($field == 'registration_url') {
854 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE);
855 }
856 elseif (in_array($field, array('start_date', 'end_date', 'join_date', 'activity_date_time'))) {
857 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date::customFormat($dao->$field);
858 }
859 elseif ($field == 'balance') {
860 if ($dao->entityTable == 'civicrm_contact') {
861 $balancePay = 'N/A';
862 }
863 elseif (!empty($dao->entityID)) {
864 $info = CRM_Contribute_BAO_Contribution::getPaymentInfo($dao->entityID, 'event');
865 $balancePay = CRM_Utils_Array::value('balance', $info);
866 $balancePay = CRM_Utils_Money::format($balancePay);
867 }
868 $entityTokenParams["{$tokenEntity}." . $field] = $balancePay;
869 }
870 elseif ($field == 'fee_amount') {
871 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Money::format($dao->$field);
872 }
873 else {
874 $entityTokenParams["{$tokenEntity}." . $field] = $dao->$field;
875 }
876 }
877
878 $isError = 0;
879 $errorMsg = $toEmail = $toPhoneNumber = '';
880
881 if ($actionSchedule->mode == 'SMS' or $actionSchedule->mode == 'User_Preference') {
882 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
883 $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($dao->contactID, FALSE, 'Mobile', $filters);
884 //to get primary mobile ph,if not get a first mobile phONE
885 if (!empty($toPhoneNumbers)) {
886 $toPhoneNumberDetails = reset($toPhoneNumbers);
887 $toPhoneNumber = CRM_Utils_Array::value('phone', $toPhoneNumberDetails);
888 //contact allows to send sms
889 $toDoNotSms = 0;
890 }
891 }
892 if ($actionSchedule->mode == 'Email' or $actionSchedule->mode == 'User_Preference') {
893 $toEmail = CRM_Contact_BAO_Contact::getPrimaryEmail($dao->contactID);
894 }
895 if ($toEmail || !(empty($toPhoneNumber) or $toDoNotSms)) {
896 $to['email'] = $toEmail;
897 $to['phone'] = $toPhoneNumber;
898 $result
899 = CRM_Core_BAO_ActionSchedule::sendReminder(
900 $dao->contactID,
901 $to,
902 $actionSchedule->id,
903 $fromEmailAddress,
904 $entityTokenParams
905 );
906
907 if (!$result || is_a($result, 'PEAR_Error')) {
908 // we could not send an email, for now we ignore, CRM-3406
909 $isError = 1;
910 }
911 }
912 else {
913 $isError = 1;
914 $errorMsg = "Couldn\'t find recipient\'s email address.";
915 }
916
917 // update action log record
918 $logParams = array(
919 'id' => $dao->reminderID,
920 'is_error' => $isError,
921 'message' => $errorMsg ? $errorMsg : "null",
922 'action_date_time' => $now,
923 );
924 CRM_Core_BAO_ActionLog::create($logParams);
925
926 // insert activity log record if needed
927 if ($actionSchedule->record_activity && !$isError) {
928 $activityParams = array(
929 'subject' => $actionSchedule->title,
930 'details' => $actionSchedule->body_html,
931 'source_contact_id' => $session->get('userID') ? $session->get('userID') : $dao->contactID,
932 'target_contact_id' => $dao->contactID,
933 'activity_date_time' => date('YmdHis'),
934 'status_id' => $activityStatusID,
935 'activity_type_id' => $activityTypeID,
936 'source_record_id' => $dao->entityID,
937 );
938 $activity = CRM_Activity_BAO_Activity::create($activityParams);
939
940 //file reminder on case if source activity is a case activity
941 if (!empty($dao->case_id)) {
942 $caseActivityParams = array();
943 $caseActivityParams['case_id'] = $dao->case_id;
944 $caseActivityParams['activity_id'] = $activity->id;
945 CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
946 }
947 }
948 }
949
950 $dao->free();
951 }
952 }
953
954 /**
955 * @param int $mappingID
956 * @param $now
957 * @param array $params
958 *
959 * @throws API_Exception
960 */
961 public static function buildRecipientContacts($mappingID, $now, $params = array()) {
962 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
963 $actionSchedule->mapping_id = $mappingID;
964 $actionSchedule->is_active = 1;
965 if (!empty($params)) {
966 _civicrm_api3_dao_set_filter($actionSchedule, $params, FALSE);
967 }
968 $actionSchedule->find();
969
970 while ($actionSchedule->fetch()) {
971 $mapping = new CRM_Core_DAO_ActionMapping();
972 $mapping->id = $mappingID;
973 $mapping->find(TRUE);
974
975 // note: $where - this filtering applies for both
976 // 'limit to' and 'addition to' options
977 // $limitWhere - this filtering applies only for
978 // 'limit to' option
979 $select = $join = $where = $limitWhere = array();
980 $selectColumns = "contact_id, entity_id, entity_table, action_schedule_id";
981 $limitTo = $actionSchedule->limit_to;
982 $value = explode(CRM_Core_DAO::VALUE_SEPARATOR,
983 trim($actionSchedule->entity_value, CRM_Core_DAO::VALUE_SEPARATOR)
984 );
985 $value = implode(',', $value);
986
987 $status = explode(CRM_Core_DAO::VALUE_SEPARATOR,
988 trim($actionSchedule->entity_status, CRM_Core_DAO::VALUE_SEPARATOR)
989 );
990 $status = implode(',', $status);
991
992 $anniversary = FALSE;
993
994 if (!CRM_Utils_System::isNull($mapping->entity_recipient)) {
995 if ($mapping->entity_recipient == 'event_contacts') {
996 $recipientOptions = CRM_Core_OptionGroup::values($mapping->entity_recipient, FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
997 }
998 else {
999 $recipientOptions = CRM_Core_OptionGroup::values($mapping->entity_recipient, FALSE, FALSE, FALSE, NULL, 'name');
1000 }
1001 }
1002 $from = "{$mapping->entity} e";
1003
1004 if ($mapping->entity == 'civicrm_activity') {
1005 $contactField = 'r.contact_id';
1006 $table = 'civicrm_activity e';
1007 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1008 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1009 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1010 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1011
1012 if (!is_null($limitTo)) {
1013 if ($limitTo == 0) {
1014 // including the activity target contacts if 'in addition' is defined
1015 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
1016 }
1017 else {
1018 switch (CRM_Utils_Array::value($actionSchedule->recipient, $recipientOptions)) {
1019 case 'Activity Assignees':
1020 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$assigneeID}";
1021 break;
1022
1023 case 'Activity Source':
1024 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$sourceID}";
1025 break;
1026
1027 default:
1028 case 'Activity Targets':
1029 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
1030 break;
1031 }
1032 }
1033 }
1034 // build where clause
1035 if (!empty($value)) {
1036 $where[] = "e.activity_type_id IN ({$value})";
1037 }
1038 else {
1039 $where[] = "e.activity_type_id IS NULL";
1040 }
1041 if (!empty($status)) {
1042 $where[] = "e.status_id IN ({$status})";
1043 }
1044 $where[] = ' e.is_current_revision = 1 ';
1045 $where[] = ' e.is_deleted = 0 ';
1046
1047 $dateField = 'e.activity_date_time';
1048 }
1049
1050 if ($mapping->entity == 'civicrm_participant') {
1051 $table = 'civicrm_event r';
1052 $contactField = 'e.contact_id';
1053 $join[] = 'INNER JOIN civicrm_event r ON e.event_id = r.id';
1054 if ($actionSchedule->recipient_listing && $limitTo) {
1055 $rList = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1056 trim($actionSchedule->recipient_listing, CRM_Core_DAO::VALUE_SEPARATOR)
1057 );
1058 $rList = implode(',', $rList);
1059
1060 switch (CRM_Utils_Array::value($actionSchedule->recipient, $recipientOptions)) {
1061 case 'participant_role':
1062 $where[] = "e.role_id IN ({$rList})";
1063 break;
1064
1065 default:
1066 break;
1067 }
1068 }
1069
1070 // build where clause
1071 if (!empty($value)) {
1072 $where[] = ($mapping->entity_value == 'event_type') ? "r.event_type_id IN ({$value})" : "r.id IN ({$value})";
1073 }
1074 else {
1075 $where[] = ($mapping->entity_value == 'event_type') ? "r.event_type_id IS NULL" : "r.id IS NULL";
1076 }
1077
1078 // participant status criteria not to be implemented
1079 // for additional recipients
1080 if (!empty($status)) {
1081 $limitWhere[] = "e.status_id IN ({$status})";
1082 }
1083
1084 $where[] = 'r.is_active = 1';
1085 $where[] = 'r.is_template = 0';
1086 $dateField = str_replace('event_', 'r.', $actionSchedule->start_action_date);
1087 }
1088
1089 $notINClause = '';
1090 if ($mapping->entity == 'civicrm_membership') {
1091 $contactField = 'e.contact_id';
1092 $table = 'civicrm_membership e';
1093 // build where clause
1094 if ($status == 2) {
1095 //auto-renew memberships
1096 $where[] = "e.contribution_recur_id IS NOT NULL ";
1097 }
1098 elseif ($status == 1) {
1099 $where[] = "e.contribution_recur_id IS NULL ";
1100 }
1101
1102 // build where clause
1103 if (!empty($value)) {
1104 $where[] = "e.membership_type_id IN ({$value})";
1105 }
1106 else {
1107 $where[] = "e.membership_type_id IS NULL";
1108 }
1109
1110 $where[] = "( e.is_override IS NULL OR e.is_override = 0 )";
1111 $dateField = str_replace('membership_', 'e.', $actionSchedule->start_action_date);
1112 $notINClause = self::permissionedRelationships($contactField);
1113
1114 $membershipStatus = CRM_Member_PseudoConstant::membershipStatus(NULL, "(is_current_member = 1 OR name = 'Expired')", 'id');
1115 $mStatus = implode(',', $membershipStatus);
1116 $where[] = "e.status_id IN ({$mStatus})";
1117
1118 // We are not tracking the reference date for 'repeated' schedule reminders,
1119 // for further details please check CRM-15376
1120 if ($actionSchedule->start_action_date && $actionSchedule->is_repeat == FALSE) {
1121 $select[] = $dateField;
1122 $selectColumns = "reference_date, " . $selectColumns;
1123 }
1124 }
1125
1126 if ($mapping->entity == 'civicrm_contact') {
1127 $contactFields = array(
1128 'birth_date',
1129 'created_date',
1130 'modified_date',
1131 );
1132 if (in_array($value, $contactFields)) {
1133 $dateDBField = $value;
1134 $table = 'civicrm_contact e';
1135 $contactField = 'e.id';
1136 $where[] = 'e.is_deleted = 0';
1137 $where[] = 'e.is_deceased = 0';
1138 }
1139 else {
1140 //custom field
1141 $customFieldParams = array('id' => substr($value, 7));
1142 $customGroup = $customField = array();
1143 CRM_Core_BAO_CustomField::retrieve($customFieldParams, $customField);
1144 $dateDBField = $customField['column_name'];
1145 $customGroupParams = array('id' => $customField['custom_group_id'], $customGroup);
1146 CRM_Core_BAO_CustomGroup::retrieve($customGroupParams, $customGroup);
1147 $from = $table = "{$customGroup['table_name']} e";
1148 $contactField = 'e.entity_id';
1149 $where[] = '1'; // possible to have no "where" in this case
1150 }
1151
1152 $status_ = explode(',', $status);
1153 if (in_array(2, $status_)) {
1154 // anniversary mode:
1155 $dateField = 'DATE_ADD(e.' . $dateDBField . ', INTERVAL ROUND(DATEDIFF(DATE(' . $now . '), e.' . $dateDBField . ') / 365) YEAR)';
1156 $anniversary = TRUE;
1157 }
1158 else {
1159 // regular mode:
1160 $dateField = 'e.' . $dateDBField;
1161 }
1162 }
1163
1164 // CRM-13577 Introduce Smart Groups Handling
1165 if ($actionSchedule->group_id) {
1166
1167 // Need to check if its a smart group or not
1168 // Then decide which table to join onto the query
1169 $group = CRM_Contact_DAO_Group::getTableName();
1170
1171 // Get the group information
1172 $sql = "
1173 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
1174 FROM $group
1175 WHERE $group.id = {$actionSchedule->group_id}
1176 ";
1177
1178 $groupDAO = CRM_Core_DAO::executeQuery($sql);
1179 $isSmartGroup = FALSE;
1180 if (
1181 $groupDAO->fetch() &&
1182 !empty($groupDAO->saved_search_id)
1183 ) {
1184 // Check that the group is in place in the cache and up to date
1185 CRM_Contact_BAO_GroupContactCache::check($actionSchedule->group_id);
1186 // Set smart group flag
1187 $isSmartGroup = TRUE;
1188 }
1189 }
1190 // CRM-13577 End Introduce Smart Groups Handling
1191
1192 if ($limitTo) {
1193 if ($actionSchedule->group_id) {
1194 // CRM-13577 If smart group then use Cache table
1195 if ($isSmartGroup) {
1196 $join[] = "INNER JOIN civicrm_group_contact_cache grp ON {$contactField} = grp.contact_id";
1197 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1198 }
1199 else {
1200 $join[] = "INNER JOIN civicrm_group_contact grp ON {$contactField} = grp.contact_id AND grp.status = 'Added'";
1201 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1202 }
1203 }
1204 elseif (!empty($actionSchedule->recipient_manual)) {
1205 $rList = CRM_Utils_Type::escape($actionSchedule->recipient_manual, 'String');
1206 $where[] = "{$contactField} IN ({$rList})";
1207 }
1208 }
1209 elseif (!is_null($limitTo)) {
1210 $addGroup = $addWhere = '';
1211 if ($actionSchedule->group_id) {
1212 // CRM-13577 If smart group then use Cache table
1213 if ($isSmartGroup) {
1214 $addGroup = " INNER JOIN civicrm_group_contact_cache grp ON c.id = grp.contact_id";
1215 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1216 }
1217 else {
1218 $addGroup = " INNER JOIN civicrm_group_contact grp ON c.id = grp.contact_id AND grp.status = 'Added'";
1219 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1220 }
1221 }
1222 if (!empty($actionSchedule->recipient_manual)) {
1223 $rList = CRM_Utils_Type::escape($actionSchedule->recipient_manual, 'String');
1224 $addWhere = "c.id IN ({$rList})";
1225 }
1226 }
1227
1228 $select[] = "{$contactField} as contact_id";
1229 $select[] = 'e.id as entity_id';
1230 $select[] = "'{$mapping->entity}' as entity_table";
1231 $select[] = "{$actionSchedule->id} as action_schedule_id";
1232 $reminderJoinClause = "civicrm_action_log reminder ON reminder.contact_id = {$contactField} AND
1233 reminder.entity_id = e.id AND
1234 reminder.entity_table = '{$mapping->entity}' AND
1235 reminder.action_schedule_id = %1";
1236
1237 if ($anniversary) {
1238 // only consider reminders less than 11 months ago
1239 $reminderJoinClause .= " AND reminder.action_date_time > DATE_SUB({$now}, INTERVAL 11 MONTH)";
1240 }
1241
1242 if ($table != 'civicrm_contact e') {
1243 $join[] = "INNER JOIN civicrm_contact c ON c.id = {$contactField} AND c.is_deleted = 0 AND c.is_deceased = 0 ";
1244 }
1245
1246 $multilingual = CRM_Core_I18n::isMultilingual();
1247 if ($multilingual && !empty($actionSchedule->filter_contact_language)) {
1248 $tableAlias = ($table != 'civicrm_contact e') ? 'c' : 'e';
1249
1250 // get language filter for the schedule
1251 $filter_contact_language = explode(CRM_Core_DAO::VALUE_SEPARATOR, $actionSchedule->filter_contact_language);
1252 $w = '';
1253 if (($key = array_search(CRM_Core_I18n::NONE, $filter_contact_language)) !== false) {
1254 $w .= "{$tableAlias}.preferred_language IS NULL OR {$tableAlias}.preferred_language = '' OR ";
1255 unset($filter_contact_language[$key]);
1256 }
1257 if (count($filter_contact_language) > 0) {
1258 $w .= "{$tableAlias}.preferred_language IN ('" . implode("','", $filter_contact_language) . "')";
1259 }
1260 $where[] = "($w)";
1261 }
1262
1263 if ($actionSchedule->start_action_date) {
1264 $startDateClause = array();
1265 $op = ($actionSchedule->start_action_condition == 'before' ? '<=' : '>=');
1266 $operator = ($actionSchedule->start_action_condition == 'before' ? 'DATE_SUB' : 'DATE_ADD');
1267 $date = $operator . "({$dateField}, INTERVAL {$actionSchedule->start_action_offset} {$actionSchedule->start_action_unit})";
1268 $startDateClause[] = "'{$now}' >= {$date}";
1269 if ($mapping->entity == 'civicrm_participant') {
1270 $startDateClause[] = $operator . "({$now}, INTERVAL 1 DAY ) {$op} " . $dateField;
1271 }
1272 else {
1273 $startDateClause[] = "DATE_SUB({$now}, INTERVAL 1 DAY ) <= {$date}";
1274 }
1275
1276 $startDate = implode(' AND ', $startDateClause);
1277 }
1278 elseif ($actionSchedule->absolute_date) {
1279 $startDate = "DATEDIFF(DATE('{$now}'),'{$actionSchedule->absolute_date}') = 0";
1280 }
1281
1282 // ( now >= date_built_from_start_time ) OR ( now = absolute_date )
1283 $dateClause = "reminder.id IS NULL AND {$startDate}";
1284
1285 // start composing query
1286 $selectClause = 'SELECT ' . implode(', ', $select);
1287 $fromClause = "FROM $from";
1288 $joinClause = !empty($join) ? implode(' ', $join) : '';
1289 $whereClause = 'WHERE ' . implode(' AND ', $where);
1290 $limitWhereClause = '';
1291 if (!empty($limitWhere)) {
1292 $limitWhereClause = ' AND ' . implode(' AND ', $limitWhere);
1293 }
1294
1295 $query = "
1296 INSERT INTO civicrm_action_log ({$selectColumns})
1297 {$selectClause}
1298 {$fromClause}
1299 {$joinClause}
1300 LEFT JOIN {$reminderJoinClause}
1301 {$whereClause} {$limitWhereClause} AND {$dateClause} {$notINClause}
1302 ";
1303
1304 // In some cases reference_date got outdated due to many reason e.g. In Membership renewal end_date got extended
1305 // which means reference date mismatches with the end_date where end_date may be used as the start_action_date
1306 // criteria for some schedule reminder so in order to send new reminder we INSERT new reminder with new reference_date
1307 // value via UNION operation
1308 if (strpos($selectColumns, 'reference_date') !== FALSE) {
1309 $dateClause = str_replace('reminder.id IS NULL', 'reminder.id IS NOT NULL', $dateClause);
1310 $referenceQuery = "
1311 INSERT INTO civicrm_action_log ({$selectColumns})
1312 {$selectClause}
1313 {$fromClause}
1314 {$joinClause}
1315 LEFT JOIN {$reminderJoinClause}
1316 {$whereClause} {$limitWhereClause} {$notINClause} AND {$dateClause} AND
1317 reminder.action_date_time IS NOT NULL AND
1318 reminder.reference_date IS NOT NULL
1319 GROUP BY reminder.id, reminder.reference_date
1320 HAVING reminder.id = MAX(reminder.id) AND reminder.reference_date <> {$dateField}
1321 ";
1322 }
1323
1324 CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer')));
1325
1326 if (!empty($referenceQuery)) {
1327 CRM_Core_DAO::executeQuery($referenceQuery, array(1 => array($actionSchedule->id, 'Integer')));
1328 }
1329
1330 $isSendToAdditionalContacts = (!is_null($limitTo) && $limitTo == 0 && (!empty($addGroup) || !empty($addWhere))) ? TRUE : FALSE;
1331 if ($isSendToAdditionalContacts) {
1332 $contactTable = "civicrm_contact c";
1333 $addSelect = "SELECT c.id as contact_id, c.id as entity_id, 'civicrm_contact' as entity_table, {$actionSchedule->id} as action_schedule_id";
1334 $additionReminderClause = "civicrm_action_log reminder ON reminder.contact_id = c.id AND
1335 reminder.entity_id = c.id AND
1336 reminder.entity_table = 'civicrm_contact' AND
1337 reminder.action_schedule_id = {$actionSchedule->id}";
1338 $addWhereClause = '';
1339 if ($addWhere) {
1340 $addWhereClause = "AND {$addWhere}";
1341 }
1342 $insertAdditionalSql = "
1343 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1344 {$addSelect}
1345 FROM ({$contactTable})
1346 LEFT JOIN {$additionReminderClause}
1347 {$addGroup}
1348 WHERE c.is_deleted = 0 AND c.is_deceased = 0
1349 {$addWhereClause}
1350
1351 AND reminder.id IS NULL
1352 AND c.id NOT IN (
1353 SELECT rem.contact_id
1354 FROM civicrm_action_log rem INNER JOIN {$mapping->entity} e ON rem.entity_id = e.id
1355 WHERE rem.action_schedule_id = {$actionSchedule->id}
1356 AND rem.entity_table = '{$mapping->entity}'
1357 )
1358 GROUP BY c.id
1359 ";
1360 CRM_Core_DAO::executeQuery($insertAdditionalSql);
1361 }
1362 // if repeat is turned ON:
1363 if ($actionSchedule->is_repeat) {
1364 $repeatEvent = ($actionSchedule->end_action == 'before' ? 'DATE_SUB' : 'DATE_ADD') . "({$dateField}, INTERVAL {$actionSchedule->end_frequency_interval} {$actionSchedule->end_frequency_unit})";
1365
1366 if ($actionSchedule->repetition_frequency_unit == 'day') {
1367 $interval = "{$actionSchedule->repetition_frequency_interval} DAY";
1368 }
1369 elseif ($actionSchedule->repetition_frequency_unit == 'week') {
1370 $interval = "{$actionSchedule->repetition_frequency_interval} WEEK";
1371 }
1372 elseif ($actionSchedule->repetition_frequency_unit == 'month') {
1373 $interval = "{$actionSchedule->repetition_frequency_interval} MONTH";
1374 }
1375 elseif ($actionSchedule->repetition_frequency_unit == 'year') {
1376 $interval = "{$actionSchedule->repetition_frequency_interval} YEAR";
1377 }
1378 else {
1379 $interval = "{$actionSchedule->repetition_frequency_interval} HOUR";
1380 }
1381
1382 // (now <= repeat_end_time )
1383 $repeatEventClause = "'{$now}' <= {$repeatEvent}";
1384 // diff(now && logged_date_time) >= repeat_interval
1385 $havingClause = "HAVING TIMESTAMPDIFF(HOUR, latest_log_time, CAST({$now} AS datetime)) >= TIMESTAMPDIFF(HOUR, latest_log_time, DATE_ADD(latest_log_time, INTERVAL $interval))";
1386 $groupByClause = 'GROUP BY reminder.contact_id, reminder.entity_id, reminder.entity_table';
1387 $selectClause .= ', MAX(reminder.action_date_time) as latest_log_time';
1388 //CRM-15376 - do not send our reminders if original criteria no longer applies
1389 // the first part of the startDateClause array is the earliest the reminder can be sent. If the
1390 // event (e.g membership_end_date) has changed then the reminder may no longer apply
1391 // @todo - this only handles events that get moved later. Potentially they might get moved earlier
1392 $originalEventStartDateClause = empty($startDateClause) ? '' : 'AND' . $startDateClause[0];
1393 $sqlInsertValues = "{$selectClause}
1394 {$fromClause}
1395 {$joinClause}
1396 INNER JOIN {$reminderJoinClause}
1397 {$whereClause} {$limitWhereClause} AND {$repeatEventClause} {$originalEventStartDateClause} {$notINClause}
1398 {$groupByClause}
1399 {$havingClause}";
1400
1401 $valsqlInsertValues = CRM_Core_DAO::executeQuery($sqlInsertValues, array(
1402 1 => array(
1403 $actionSchedule->id,
1404 'Integer',
1405 ),
1406 )
1407 );
1408
1409 $arrValues = array();
1410 while ($valsqlInsertValues->fetch()) {
1411 $arrValues[] = "( {$valsqlInsertValues->contact_id}, {$valsqlInsertValues->entity_id}, '{$valsqlInsertValues->entity_table}',{$valsqlInsertValues->action_schedule_id} )";
1412 }
1413
1414 $valString = implode(',', $arrValues);
1415
1416 if ($valString) {
1417 $query = '
1418 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1419 CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer')));
1420 }
1421
1422 if ($isSendToAdditionalContacts) {
1423 $addSelect .= ', MAX(reminder.action_date_time) as latest_log_time';
1424 $sqlEndEventCheck = "
1425 SELECT * FROM {$table}
1426 {$whereClause} AND {$repeatEventClause} LIMIT 1";
1427
1428 $daoCheck = CRM_Core_DAO::executeQuery($sqlEndEventCheck);
1429 if ($daoCheck->fetch()) {
1430 $valSqlAdditionInsert = "
1431 {$addSelect}
1432 FROM {$contactTable}
1433 {$addGroup}
1434 INNER JOIN {$additionReminderClause}
1435 WHERE {$addWhere} AND c.is_deleted = 0 AND c.is_deceased = 0
1436 GROUP BY reminder.contact_id
1437 {$havingClause}
1438 ";
1439 $daoForVals = CRM_Core_DAO::executeQuery($valSqlAdditionInsert);
1440 $addValues = array();
1441 while ($daoForVals->fetch()) {
1442 $addValues[] = "( {$daoForVals->contact_id}, {$daoForVals->entity_id}, '{$daoForVals->entity_table}',{$daoForVals->action_schedule_id} )";
1443 }
1444 $valString = implode(',', $addValues);
1445
1446 if ($valString) {
1447 $query = '
1448 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1449 CRM_Core_DAO::executeQuery($query);
1450 }
1451 }
1452 }
1453 }
1454 }
1455 }
1456
1457 /**
1458 * @param $field
1459 *
1460 * @return null|string
1461 */
1462 public static function permissionedRelationships($field) {
1463 $query = '
1464 SELECT cm.id AS owner_id, cm.contact_id AS owner_contact, m.id AS slave_id, m.contact_id AS slave_contact, cmt.relationship_type_id AS relation_type, rel.contact_id_a, rel.contact_id_b, rel.is_permission_a_b, rel.is_permission_b_a
1465 FROM civicrm_membership m
1466 LEFT JOIN civicrm_membership cm ON cm.id = m.owner_membership_id
1467 LEFT JOIN civicrm_membership_type cmt ON cmt.id = m.membership_type_id
1468 LEFT JOIN civicrm_relationship rel ON ( ( rel.contact_id_a = m.contact_id AND rel.contact_id_b = cm.contact_id AND rel.relationship_type_id = cmt.relationship_type_id )
1469 OR ( rel.contact_id_a = cm.contact_id AND rel.contact_id_b = m.contact_id AND rel.relationship_type_id = cmt.relationship_type_id ) )
1470 WHERE m.owner_membership_id IS NOT NULL AND
1471 ( rel.is_permission_a_b = 0 OR rel.is_permission_b_a = 0)
1472
1473 ';
1474 $excludeIds = array();
1475 $dao = CRM_Core_DAO::executeQuery($query, array());
1476 while ($dao->fetch()) {
1477 if ($dao->slave_contact == $dao->contact_id_a && $dao->is_permission_a_b == 0) {
1478 $excludeIds[] = $dao->slave_contact;
1479 }
1480 elseif ($dao->slave_contact == $dao->contact_id_b && $dao->is_permission_b_a == 0) {
1481 $excludeIds[] = $dao->slave_contact;
1482 }
1483 }
1484
1485 if (!empty($excludeIds)) {
1486 $clause = "AND {$field} NOT IN ( " . implode(', ', $excludeIds) . ' ) ';
1487 return $clause;
1488 }
1489 return NULL;
1490 }
1491
1492 /**
1493 * @param null $now
1494 * @param array $params
1495 *
1496 * @return array
1497 */
1498 public static function processQueue($now = NULL, $params = array()) {
1499 $now = $now ? CRM_Utils_Time::setTime($now) : CRM_Utils_Time::getTime();
1500
1501 $mappings = self::getMapping();
1502 foreach ($mappings as $mappingID => $mapping) {
1503 self::buildRecipientContacts($mappingID, $now, $params);
1504 self::sendMailings($mappingID, $now);
1505 }
1506
1507 $result = array(
1508 'is_error' => 0,
1509 'messages' => ts('Sent all scheduled reminders successfully'),
1510 );
1511 return $result;
1512 }
1513
1514 /**
1515 * @param int $id
1516 * @param int $mappingID
1517 *
1518 * @return null|string
1519 */
1520 public static function isConfigured($id, $mappingID) {
1521 $queryString = "SELECT count(id) FROM civicrm_action_schedule
1522 WHERE mapping_id = %1 AND
1523 entity_value = %2";
1524
1525 $params = array(
1526 1 => array($mappingID, 'Integer'),
1527 2 => array($id, 'Integer'),
1528 );
1529 return CRM_Core_DAO::singleValueQuery($queryString, $params);
1530 }
1531
1532 /**
1533 * @param int $mappingID
1534 * @param $recipientType
1535 *
1536 * @return array
1537 */
1538 public static function getRecipientListing($mappingID, $recipientType) {
1539 $options = array();
1540 if (!$mappingID || !$recipientType) {
1541 return $options;
1542 }
1543
1544 $mapping = self::getMapping($mappingID);
1545
1546 switch ($mapping['entity']) {
1547 case 'civicrm_participant':
1548 $eventContacts = CRM_Core_OptionGroup::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
1549 if (empty($eventContacts[$recipientType])) {
1550 return $options;
1551 }
1552 if ($eventContacts[$recipientType] == 'participant_role') {
1553 $options = CRM_Event_PseudoConstant::participantRole();
1554 }
1555 break;
1556 }
1557
1558 return $options;
1559 }
1560
1561 /**
1562 * @param $communication_language
1563 * @param $preferred_language
1564 */
1565 public static function setCommunicationLanguage($communication_language, $preferred_language) {
1566 $config = CRM_Core_Config::singleton();
1567 $language = $config->lcMessages;
1568
1569 // prepare the language for the email
1570 if ($communication_language == CRM_Core_I18n::AUTO) {
1571 if (!empty($preferred_language)) {
1572 $language = $preferred_language;
1573 }
1574 }
1575 else {
1576 $language = $communication_language;
1577 }
1578
1579 // language not in the existing language, use default
1580 $languages = CRM_Core_I18n::languages(TRUE);
1581 if (!in_array($language, $languages)) {
1582 $language = $config->lcMessages;
1583 }
1584
1585 // change the language
1586 $i18n = CRM_Core_I18n::singleton();
1587 $i18n->setLanguage($language);
1588 }
1589
1590 }