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