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