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