Merge branch '4.5' of https://github.com/civicrm/civicrm-core
[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 int $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();
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 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', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name');
196 $sel5[$entityRecipient] = $eventContacts + $options;
197 $recipientMapping += CRM_Core_OptionGroup::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, '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 int $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 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', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name');
299 $sel5[$id] = $eventContacts + $options;
300 $recipientMapping += CRM_Core_OptionGroup::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, '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 int $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 $where = " WHERE 1 ";
371 if ($entityValue and $id) {
372 $where .= "
373 AND cas.entity_value = $id AND
374 cam.entity_value = '$entityValue'";
375
376 $params = array(
377 1 => array($id, 'Integer'),
378 2 => array($entityValue, 'String'),
379 );
380 }
381 $where .= " AND cas.used_for IS NULL";
382 $query .= $where;
383 $dao = CRM_Core_DAO::executeQuery($query);
384 while ($dao->fetch()) {
385 $list[$dao->id]['id'] = $dao->id;
386 $list[$dao->id]['title'] = $dao->title;
387 $list[$dao->id]['start_action_offset'] = $dao->start_action_offset;
388 $list[$dao->id]['start_action_unit'] = $dao->start_action_unit;
389 $list[$dao->id]['start_action_condition'] = $dao->start_action_condition;
390 $list[$dao->id]['entityDate'] = ucwords(str_replace('_', ' ', $dao->entityDate));
391 $list[$dao->id]['absolute_date'] = $dao->absolute_date;
392
393 $status = $dao->entityStatus;
394 $statusArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $dao->entityStatusIds);
395 foreach ($statusArray as & $s) {
396 $s = CRM_Utils_Array::value($s, $$status);
397 }
398 $statusIds = implode(', ', $statusArray);
399
400 $value = $dao->entityValue;
401 $valueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $dao->entityValueIds);
402 foreach ($valueArray as & $v) {
403 $v = CRM_Utils_Array::value($v, $$value);
404 }
405 $valueIds = implode(', ', $valueArray);
406 $list[$dao->id]['entity'] = $entity[$dao->entity];
407 $list[$dao->id]['value'] = $valueIds;
408 $list[$dao->id]['status'] = $statusIds;
409 $list[$dao->id]['is_repeat'] = $dao->is_repeat;
410 $list[$dao->id]['is_active'] = $dao->is_active;
411 }
412
413 return $list;
414 }
415
416 /**
417 * @param int $contactId
418 * @param $to
419 * @param int $scheduleID
420 * @param $from
421 * @param array $tokenParams
422 *
423 * @return bool|null
424 * @throws CRM_Core_Exception
425 */
426 static function sendReminder($contactId, $to, $scheduleID, $from, $tokenParams) {
427 $email = $to['email'];
428 $phoneNumber = $to['phone'];
429 $schedule = new CRM_Core_DAO_ActionSchedule();
430 $schedule->id = $scheduleID;
431
432 $domain = CRM_Core_BAO_Domain::getDomain();
433 $result = NULL;
434 $hookTokens = array();
435
436 if ($schedule->find(TRUE)) {
437 $body_text = $schedule->body_text;
438 $body_html = $schedule->body_html;
439 $sms_body_text = $schedule->sms_body_text;
440 $body_subject = $schedule->subject;
441 if (!$body_text) {
442 $body_text = CRM_Utils_String::htmlToText($body_html);
443 }
444
445 $params = array(array('contact_id', '=', $contactId, 0, 0));
446 list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($params);
447
448 //CRM-4524
449 $contact = reset($contact);
450
451 if (!$contact || is_a($contact, 'CRM_Core_Error')) {
452 return NULL;
453 }
454
455 // merge activity tokens with contact array
456 $contact = array_merge($contact, $tokenParams);
457
458 //CRM-5734
459 CRM_Utils_Hook::tokenValues($contact, $contactId);
460
461 CRM_Utils_Hook::tokens($hookTokens);
462 $categories = array_keys($hookTokens);
463
464 $type = array('body_html' => 'html', 'body_text' => 'text', 'sms_body_text' => 'text');
465
466 foreach ($type as $bodyType => $value) {
467 $dummy_mail = new CRM_Mailing_BAO_Mailing();
468 if ($bodyType == 'sms_body_text') {
469 $dummy_mail->body_text = $$bodyType;
470 }
471 else {
472 $dummy_mail->$bodyType = $$bodyType;
473 }
474 $tokens = $dummy_mail->getTokens();
475
476 if ($$bodyType) {
477 CRM_Utils_Token::replaceGreetingTokens($$bodyType, NULL, $contact['contact_id']);
478 $$bodyType = CRM_Utils_Token::replaceDomainTokens($$bodyType, $domain, TRUE, $tokens[$value], TRUE);
479 $$bodyType = CRM_Utils_Token::replaceContactTokens($$bodyType, $contact, FALSE, $tokens[$value], FALSE, TRUE);
480 $$bodyType = CRM_Utils_Token::replaceComponentTokens($$bodyType, $contact, $tokens[$value], TRUE, FALSE);
481 $$bodyType = CRM_Utils_Token::replaceHookTokens($$bodyType, $contact, $categories, TRUE);
482 }
483 }
484 $html = $body_html;
485 $text = $body_text;
486 $sms_text = $sms_body_text;
487
488 $smarty = CRM_Core_Smarty::singleton();
489 foreach (array(
490 'text', 'html', 'sms_text') as $elem) {
491 $$elem = $smarty->fetch("string:{$$elem}");
492 }
493
494 $matches = array();
495 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
496 $body_subject,
497 $matches,
498 PREG_PATTERN_ORDER
499 );
500
501 $subjectToken = NULL;
502 if ($matches[1]) {
503 foreach ($matches[1] as $token) {
504 list($type, $name) = preg_split('/\./', $token, 2);
505 if ($name) {
506 if (!isset($subjectToken[$type])) {
507 $subjectToken[$type] = array();
508 }
509 $subjectToken[$type][] = $name;
510 }
511 }
512 }
513
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 * @access public
588 * @static
589 *
590 */
591 static function add(&$params, $ids = array()) {
592 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
593 $actionSchedule->copyValues($params);
594
595 return $actionSchedule->save();
596 }
597
598 /**
599 * Takes a bunch of params that are needed to match certain criteria and
600 * retrieves the relevant objects. It also stores all the retrieved
601 * values in the default array
602 *
603 * @param array $params (reference ) an assoc array of name/value pairs
604 * @param array $values (reference ) an assoc array to hold the flattened values
605 *
606 * @return CRM_Core_DAO_ActionSchedule object on success, null otherwise
607 * @access public
608 * @static
609 */
610 static function retrieve(&$params, &$values) {
611 if (empty($params)) {
612 return NULL;
613 }
614 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
615
616 $actionSchedule->copyValues($params);
617
618 if ($actionSchedule->find(TRUE)) {
619 $ids['actionSchedule'] = $actionSchedule->id;
620
621 CRM_Core_DAO::storeValues($actionSchedule, $values);
622
623 return $actionSchedule;
624 }
625 return NULL;
626 }
627
628 /**
629 * Delete a Reminder
630 *
631 * @param int $id ID of the Reminder to be deleted.
632 *
633 * @access public
634 * @static
635 */
636 static function del($id) {
637 if ($id) {
638 $dao = new CRM_Core_DAO_ActionSchedule();
639 $dao->id = $id;
640 if ($dao->find(TRUE)) {
641 $dao->delete();
642 return;
643 }
644 }
645 CRM_Core_Error::fatal(ts('Invalid value passed to delete function.'));
646 }
647
648 /**
649 * Update the is_active flag in the db
650 *
651 * @param int $id id of the database record
652 * @param boolean $is_active value we want to set the is_active field
653 *
654 * @return Object DAO object on success, null otherwise
655 * @static
656 */
657 static function setIsActive($id, $is_active) {
658 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
659 }
660
661 /**
662 * @param int $mappingID
663 * @param $now
664 *
665 * @throws CRM_Core_Exception
666 */
667 static function sendMailings($mappingID, $now) {
668 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
669 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
670
671 $mapping = new CRM_Core_DAO_ActionMapping();
672 $mapping->id = $mappingID;
673 $mapping->find(TRUE);
674
675 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
676 $actionSchedule->mapping_id = $mappingID;
677 $actionSchedule->is_active = 1;
678 $actionSchedule->find(FALSE);
679
680 $tokenFields = array();
681 $session = CRM_Core_Session::singleton();
682
683 while ($actionSchedule->fetch()) {
684 $extraSelect = $extraJoin = $extraWhere = $extraOn = '';
685
686 if ($actionSchedule->from_email)
687 $fromEmailAddress = "$actionSchedule->from_name <$actionSchedule->from_email>";
688
689 $activityTypeID = false;
690 $activityStatusID = false;
691 if ($actionSchedule->record_activity) {
692 if ($mapping->entity == 'civicrm_membership') {
693 $activityTypeID =
694 CRM_Core_OptionGroup::getValue('activity_type', 'Membership Renewal Reminder', 'name');
695 }
696 else {
697 $activityTypeID =
698 CRM_Core_OptionGroup::getValue('activity_type', 'Reminder Sent', 'name');
699 }
700
701 $activityStatusID =
702 CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name');
703 }
704
705 if ($mapping->entity == 'civicrm_activity') {
706 $compInfo = CRM_Core_Component::getEnabledComponents();
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 //join for caseId
721 // if CiviCase component is enabled
722 if (array_key_exists('CiviCase', $compInfo)) {
723 $extraSelect .= ", civicrm_case_activity.case_id as case_id";
724 $extraJoin .= "
725 LEFT JOIN `civicrm_case_activity` ON `e`.`id` = `civicrm_case_activity`.`activity_id`";
726 }
727 }
728
729 if ($mapping->entity == 'civicrm_participant') {
730 $tokenEntity = 'event';
731 $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');
732 $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 ';
733
734 $extraJoin = "
735 INNER JOIN civicrm_event ev ON e.event_id = ev.id
736 INNER JOIN civicrm_option_group og ON og.name = 'event_type'
737 INNER JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
738 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
739 LEFT JOIN civicrm_address address ON address.id = lb.address_id
740 LEFT JOIN civicrm_email email ON email.id = lb.email_id
741 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
742 ";
743 if ($actionSchedule->limit_to == 0) {
744 $extraJoin = "
745 LEFT JOIN civicrm_event ev ON e.event_id = ev.id
746 LEFT JOIN civicrm_option_group og ON og.name = 'event_type'
747 LEFT JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
748 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
749 LEFT JOIN civicrm_address address ON address.id = lb.address_id
750 LEFT JOIN civicrm_email email ON email.id = lb.email_id
751 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
752 ";
753 }
754 }
755
756 if ($mapping->entity == 'civicrm_membership') {
757 $tokenEntity = 'membership';
758 $tokenFields = array('fee', 'id', 'join_date', 'start_date', 'end_date', 'status', 'type');
759 $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';
760 $extraJoin = '
761 INNER JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
762 INNER JOIN civicrm_membership_status ms ON e.status_id = ms.id';
763
764 if ($actionSchedule->limit_to == 0) {
765 $extraJoin = '
766 LEFT JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
767 LEFT JOIN civicrm_membership_status ms ON e.status_id = ms.id';
768 }
769 }
770
771 if ($mapping->entity == 'civicrm_contact') {
772 $tokenEntity = 'contact';
773 //TODO: get full list somewhere!
774 $tokenFields = array('birth_date', 'last_name');
775 //TODO: is there anything to add here?
776 }
777
778 $entityJoinClause = "INNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
779 if ($actionSchedule->limit_to == 0) {
780 $entityJoinClause = "LEFT JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
781 $extraWhere .= " AND (e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact')";
782 }
783 $entityJoinClause .= $extraOn;
784
785 $query = "
786 SELECT reminder.id as reminderID, reminder.contact_id as contactID, reminder.entity_table as entityTable, reminder.*, e.id as entityID, e.* {$extraSelect}
787 FROM civicrm_action_log reminder
788 {$entityJoinClause}
789 {$extraJoin}
790 WHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL
791 {$extraWhere}";
792
793 $dao = CRM_Core_DAO::executeQuery($query,
794 array(1 => array($actionSchedule->id, 'Integer'))
795 );
796
797 while ($dao->fetch()) {
798 $entityTokenParams = array();
799 foreach ($tokenFields as $field) {
800 if ($field == 'location') {
801 $loc = array();
802 $stateProvince = CRM_Core_PseudoConstant::stateProvince();
803 $loc['street_address'] = $dao->street_address;
804 $loc['city'] = $dao->city;
805 $loc['state_province'] = CRM_Utils_Array::value($dao->state_province_id, $stateProvince);
806 $loc['postal_code'] = $dao->postal_code;
807 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address::format($loc);
808 }
809 elseif ($field == 'info_url') {
810 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE);
811 }
812 elseif ($field == 'registration_url') {
813 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE);
814 }
815 elseif (in_array($field, array('start_date','end_date','join_date','activity_date_time'))) {
816 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date::customFormat($dao->$field);
817 }
818 elseif ($field == 'balance') {
819 if ($dao->entityTable == 'civicrm_contact') {
820 $balancePay = 'N/A';
821 }
822 elseif (!empty($dao->entityID)) {
823 $info = CRM_Contribute_BAO_Contribution::getPaymentInfo($dao->entityID, 'event');
824 $balancePay = CRM_Utils_Array::value('balance', $info);
825 $balancePay = CRM_Utils_Money::format($balancePay);
826 }
827 $entityTokenParams["{$tokenEntity}." . $field] = $balancePay;
828 }
829 elseif ($field == 'fee_amount') {
830 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Money::format($dao->$field);
831 }
832 else {
833 $entityTokenParams["{$tokenEntity}." . $field] = $dao->$field;
834 }
835 }
836
837 $isError = 0;
838 $errorMsg = $toEmail = $toPhoneNumber = '';
839
840 if ($actionSchedule->mode == 'SMS' or $actionSchedule->mode == 'User_Preference') {
841 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
842 $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($dao->contactID, FALSE, 'Mobile', $filters);
843 //to get primary mobile ph,if not get a first mobile phONE
844 if (!empty($toPhoneNumbers)) {
845 $toPhoneNumberDetails = reset($toPhoneNumbers);
846 $toPhoneNumber = CRM_Utils_Array::value('phone', $toPhoneNumberDetails);
847 //contact allows to send sms
848 $toDoNotSms = 0;
849 }
850 }
851 if ($actionSchedule->mode == 'Email' or $actionSchedule->mode == 'User_Preference') {
852 $toEmail = CRM_Contact_BAO_Contact::getPrimaryEmail($dao->contactID);
853 }
854 if ($toEmail || !(empty($toPhoneNumber) or $toDoNotSms)) {
855 $to['email'] = $toEmail;
856 $to['phone'] = $toPhoneNumber;
857 $result =
858 CRM_Core_BAO_ActionSchedule::sendReminder(
859 $dao->contactID,
860 $to,
861 $actionSchedule->id,
862 $fromEmailAddress,
863 $entityTokenParams
864 );
865
866 if (!$result || is_a($result, 'PEAR_Error')) {
867 // we could not send an email, for now we ignore, CRM-3406
868 $isError = 1;
869 }
870 }
871 else {
872 $isError = 1;
873 $errorMsg = "Couldn\'t find recipient\'s email address.";
874 }
875
876 // update action log record
877 $logParams = array(
878 'id' => $dao->reminderID,
879 'is_error' => $isError,
880 'message' => $errorMsg ? $errorMsg : "null",
881 'action_date_time' => $now,
882 );
883 CRM_Core_BAO_ActionLog::create($logParams);
884
885 // insert activity log record if needed
886 if ($actionSchedule->record_activity && !$isError) {
887 $activityParams = array(
888 'subject' => $actionSchedule->title,
889 'details' => $actionSchedule->body_html,
890 'source_contact_id' =>
891 $session->get('userID') ? $session->get('userID') : $dao->contactID,
892 'target_contact_id' => $dao->contactID,
893 'activity_date_time' => date('YmdHis'),
894 'status_id' => $activityStatusID,
895 'activity_type_id' => $activityTypeID,
896 'source_record_id' => $dao->entityID,
897 );
898 $activity = CRM_Activity_BAO_Activity::create($activityParams);
899
900 //file reminder on case if source activity is a case activity
901 if (!empty($dao->case_id)) {
902 $caseActivityParams = array();
903 $caseActivityParams['case_id'] = $dao->case_id;
904 $caseActivityParams['activity_id'] = $activity->id;
905 CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
906 }
907 }
908 }
909
910 $dao->free();
911 }
912 }
913
914 /**
915 * @param int $mappingID
916 * @param $now
917 * @param array $params
918 *
919 * @throws API_Exception
920 */
921 static function buildRecipientContacts($mappingID, $now, $params = array()) {
922 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
923 $actionSchedule->mapping_id = $mappingID;
924 $actionSchedule->is_active = 1;
925 if(!empty($params)) {
926 _civicrm_api3_dao_set_filter($actionSchedule, $params, FALSE, 'ActionSchedule');
927 }
928 $actionSchedule->find();
929
930 while ($actionSchedule->fetch()) {
931 $mapping = new CRM_Core_DAO_ActionMapping();
932 $mapping->id = $mappingID;
933 $mapping->find(TRUE);
934
935 // note: $where - this filtering applies for both
936 // 'limit to' and 'addition to' options
937 // $limitWhere - this filtering applies only for
938 // 'limit to' option
939 $select = $join = $where = $limitWhere = array();
940 $limitTo = $actionSchedule->limit_to;
941 $value = explode(CRM_Core_DAO::VALUE_SEPARATOR,
942 trim($actionSchedule->entity_value, CRM_Core_DAO::VALUE_SEPARATOR)
943 );
944 $value = implode(',', $value);
945
946 $status = explode(CRM_Core_DAO::VALUE_SEPARATOR,
947 trim($actionSchedule->entity_status, CRM_Core_DAO::VALUE_SEPARATOR)
948 );
949 $status = implode(',', $status);
950
951 $anniversary = false;
952
953 if (!CRM_Utils_System::isNull($mapping->entity_recipient)) {
954 if ($mapping->entity_recipient == 'event_contacts') {
955 $recipientOptions = CRM_Core_OptionGroup::values($mapping->entity_recipient, FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
956 }
957 else {
958 $recipientOptions = CRM_Core_OptionGroup::values($mapping->entity_recipient, FALSE, FALSE, FALSE, NULL, 'name');
959 }
960 }
961 $from = "{$mapping->entity} e";
962
963 if ($mapping->entity == 'civicrm_activity') {
964 $contactField = 'r.contact_id';
965 $table = 'civicrm_activity e';
966 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
967 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
968 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
969 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
970
971 if (!is_null($limitTo)) {
972 if ($limitTo == 0) {
973 // including the activity target contacts if 'in addition' is defined
974 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
975 }
976 else {
977 switch (CRM_Utils_Array::value($actionSchedule->recipient, $recipientOptions)) {
978 case 'Activity Assignees':
979 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$assigneeID}";
980 break;
981
982 case 'Activity Source':
983 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$sourceID}";
984 break;
985
986 default:
987 case 'Activity Targets':
988 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
989 break;
990 }
991 }
992 }
993 // build where clause
994 if (!empty($value)) {
995 $where[] = "e.activity_type_id IN ({$value})";
996 }
997 else {
998 $where[] = "e.activity_type_id IS NULL";
999 }
1000 if (!empty($status)) {
1001 $where[] = "e.status_id IN ({$status})";
1002 }
1003 $where[] = ' e.is_current_revision = 1 ';
1004 $where[] = ' e.is_deleted = 0 ';
1005
1006 $dateField = 'e.activity_date_time';
1007 }
1008
1009 if ($mapping->entity == 'civicrm_participant') {
1010 $table = 'civicrm_event r';
1011 $contactField = 'e.contact_id';
1012 $join[] = 'INNER JOIN civicrm_event r ON e.event_id = r.id';
1013 if ($actionSchedule->recipient_listing && $limitTo) {
1014 $rList = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1015 trim($actionSchedule->recipient_listing, CRM_Core_DAO::VALUE_SEPARATOR)
1016 );
1017 $rList = implode(',', $rList);
1018
1019 switch ($recipientOptions[$actionSchedule->recipient]) {
1020 case 'participant_role':
1021 $where[] = "e.role_id IN ({$rList})";
1022 break;
1023
1024 default:
1025 break;
1026 }
1027 }
1028
1029 // build where clause
1030 if (!empty($value)) {
1031 $where[] = ($mapping->entity_value == 'event_type') ? "r.event_type_id IN ({$value})" : "r.id IN ({$value})";
1032 }
1033 else {
1034 $where[] = ($mapping->entity_value == 'event_type') ? "r.event_type_id IS NULL" : "r.id IS NULL";
1035 }
1036
1037 // participant status criteria not to be implemented
1038 // for additional recipients
1039 if (!empty($status)) {
1040 $limitWhere[] = "e.status_id IN ({$status})";
1041 }
1042
1043 $where[] = 'r.is_active = 1';
1044 $where[] = 'r.is_template = 0';
1045 $dateField = str_replace('event_', 'r.', $actionSchedule->start_action_date);
1046 }
1047
1048 $notINClause = '';
1049 if ($mapping->entity == 'civicrm_membership') {
1050 $contactField = 'e.contact_id';
1051 $table = 'civicrm_membership e';
1052 // build where clause
1053 if ( $status == 2 ) {
1054 //auto-renew memberships
1055 $where[] = "e.contribution_recur_id IS NOT NULL ";
1056 }
1057 elseif ( $status == 1 ) {
1058 $where[] = "e.contribution_recur_id IS NULL ";
1059 }
1060
1061 // build where clause
1062 if (!empty($value)) {
1063 $where[] = "e.membership_type_id IN ({$value})";
1064 }
1065 else {
1066 $where[] = "e.membership_type_id IS NULL";
1067 }
1068
1069 $where[] = "( e.is_override IS NULL OR e.is_override = 0 )";
1070 $dateField = str_replace('membership_', 'e.', $actionSchedule->start_action_date);
1071 $notINClause = self::permissionedRelationships($contactField);
1072
1073 $membershipStatus = CRM_Member_PseudoConstant::membershipStatus(NULL, "(is_current_member = 1 OR name = 'Expired')", 'id');
1074 $mStatus = implode (',', $membershipStatus);
1075 $where[] = "e.status_id IN ({$mStatus})";
1076 }
1077
1078 if ($mapping->entity == 'civicrm_contact') {
1079 if ($value == 'birth_date') {
1080 $dateDBField = 'birth_date';
1081 $table = 'civicrm_contact e';
1082 $contactField = 'e.id';
1083 $where[] = 'e.is_deleted = 0';
1084 $where[] = 'e.is_deceased = 0';
1085 }
1086 else {
1087 //custom field
1088 $customFieldParams = array('id' => substr($value, 7));
1089 $customGroup = $customField = array();
1090 CRM_Core_BAO_CustomField::retrieve($customFieldParams, $customField);
1091 $dateDBField = $customField['column_name'];
1092 $customGroupParams = array('id' => $customField['custom_group_id'], $customGroup);
1093 CRM_Core_BAO_CustomGroup::retrieve($customGroupParams, $customGroup);
1094 $from = $table = "{$customGroup['table_name']} e";
1095 $contactField = 'e.entity_id';
1096 $where[] = '1'; // possible to have no "where" in this case
1097 }
1098
1099 $status_ = explode(',', $status);
1100 if (in_array(2, $status_)) {
1101 // anniversary mode:
1102 $dateField = 'DATE_ADD(e.' . $dateDBField . ', INTERVAL ROUND(DATEDIFF(DATE(' . $now . '), e.' . $dateDBField . ') / 365) YEAR)';
1103 $anniversary = true;
1104 }
1105 else {
1106 // regular mode:
1107 $dateField = 'e.' . $dateDBField;
1108 }
1109 // TODO get this working
1110
1111 // TODO: Make sure everything's provided for repetition, etc.
1112 }
1113
1114 // CRM-13577 Introduce Smart Groups Handling
1115 if ($actionSchedule->group_id) {
1116
1117 // Need to check if its a smart group or not
1118 // Then decide which table to join onto the query
1119 $group = CRM_Contact_DAO_Group::getTableName();
1120
1121 // Get the group information
1122 $sql = "
1123 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
1124 FROM $group
1125 WHERE $group.id = {$actionSchedule->group_id}
1126 ";
1127
1128 $groupDAO = CRM_Core_DAO::executeQuery($sql);
1129 $isSmartGroup = FALSE;
1130 if (
1131 $groupDAO->fetch() &&
1132 !empty($groupDAO->saved_search_id)
1133 ) {
1134 // Check that the group is in place in the cache and up to date
1135 CRM_Contact_BAO_GroupContactCache::check($actionSchedule->group_id);
1136 // Set smart group flag
1137 $isSmartGroup = TRUE;
1138 }
1139 }
1140 // CRM-13577 End Introduce Smart Groups Handling
1141
1142 if ($limitTo) {
1143 if ($actionSchedule->group_id) {
1144 // CRM-13577 If smart group then use Cache table
1145 if ($isSmartGroup) {
1146 $join[] = "INNER JOIN civicrm_group_contact_cache grp ON {$contactField} = grp.contact_id";
1147 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1148 } else {
1149 $join[] = "INNER JOIN civicrm_group_contact grp ON {$contactField} = grp.contact_id AND grp.status = 'Added'";
1150 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
1151 }
1152 }
1153 elseif (!empty($actionSchedule->recipient_manual)) {
1154 $rList = CRM_Utils_Type::escape($actionSchedule->recipient_manual, 'String');
1155 $where[] = "{$contactField} IN ({$rList})";
1156 }
1157 }
1158 elseif (!is_null($limitTo)) {
1159 $addGroup = $addWhere = '';
1160 if ($actionSchedule->group_id) {
1161 // CRM-13577 If smart group then use Cache table
1162 if ($isSmartGroup) {
1163 $addGroup = " INNER JOIN civicrm_group_contact_cache grp ON c.id = grp.contact_id";
1164 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1165 } else {
1166 $addGroup = " INNER JOIN civicrm_group_contact grp ON c.id = grp.contact_id AND grp.status = 'Added'";
1167 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1168 }
1169 }
1170 if (!empty($actionSchedule->recipient_manual)) {
1171 $rList = CRM_Utils_Type::escape($actionSchedule->recipient_manual, 'String');
1172 $addWhere = "c.id IN ({$rList})";
1173 }
1174 }
1175
1176 $select[] = "{$contactField} as contact_id";
1177 $select[] = 'e.id as entity_id';
1178 $select[] = "'{$mapping->entity}' as entity_table";
1179 $select[] = "{$actionSchedule->id} as action_schedule_id";
1180 $reminderJoinClause = "civicrm_action_log reminder ON reminder.contact_id = {$contactField} AND
1181 reminder.entity_id = e.id AND
1182 reminder.entity_table = '{$mapping->entity}' AND
1183 reminder.action_schedule_id = %1";
1184
1185 if ($anniversary) {
1186 // only consider reminders less than 11 months ago
1187 $reminderJoinClause .= " AND reminder.action_date_time > DATE_SUB({$now}, INTERVAL 11 MONTH)";
1188 }
1189
1190 if ($table != 'civicrm_contact e') {
1191 $join[] = "INNER JOIN civicrm_contact c ON c.id = {$contactField} AND c.is_deleted = 0 AND c.is_deceased = 0 ";
1192 }
1193
1194 if ($actionSchedule->start_action_date) {
1195 $startDateClause = array();
1196 $op = ($actionSchedule->start_action_condition == 'before' ? '<=' : '>=');
1197 $operator = ($actionSchedule->start_action_condition == 'before' ? 'DATE_SUB' : 'DATE_ADD');
1198 $date = $operator . "({$dateField}, INTERVAL {$actionSchedule->start_action_offset} {$actionSchedule->start_action_unit})";
1199 $startDateClause[] = "'{$now}' >= {$date}";
1200 if ($mapping->entity == 'civicrm_participant') {
1201 $startDateClause[] = $operator. "({$now}, INTERVAL 1 DAY ) {$op} " . $dateField;
1202 }
1203 else {
1204 $startDateClause[] = "DATE_SUB({$now}, INTERVAL 1 DAY ) <= {$date}";
1205 }
1206
1207 $startDate = implode(' AND ', $startDateClause);
1208 }
1209 elseif ($actionSchedule->absolute_date) {
1210 $startDate = "DATEDIFF(DATE('{$now}'),'{$actionSchedule->absolute_date}') = 0";
1211 }
1212
1213 // ( now >= date_built_from_start_time ) OR ( now = absolute_date )
1214 $dateClause = "reminder.id IS NULL AND {$startDate}";
1215
1216 // start composing query
1217 $selectClause = 'SELECT ' . implode(', ', $select);
1218 $fromClause = "FROM $from";
1219 $joinClause = !empty($join) ? implode(' ', $join) : '';
1220 $whereClause = 'WHERE ' . implode(' AND ', $where);
1221 $limitWhereClause = '';
1222 if (!empty($limitWhere)) {
1223 $limitWhereClause = ' AND ' . implode(' AND ', $limitWhere);
1224 }
1225
1226 $query = "
1227 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1228 {$selectClause}
1229 {$fromClause}
1230 {$joinClause}
1231 LEFT JOIN {$reminderJoinClause}
1232 {$whereClause} {$limitWhereClause} AND {$dateClause} {$notINClause}
1233 ";
1234 CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer')));
1235 $isSendToAdditionalContacts = (!is_null($limitTo) && $limitTo == 0 && (!empty($addGroup) || !empty($addWhere))) ? TRUE : FALSE;
1236 if ($isSendToAdditionalContacts) {
1237 $contactTable = "civicrm_contact c";
1238 $addSelect = "SELECT c.id as contact_id, c.id as entity_id, 'civicrm_contact' as entity_table, {$actionSchedule->id} as action_schedule_id";
1239 $additionReminderClause = "civicrm_action_log reminder ON reminder.contact_id = c.id AND
1240 reminder.entity_id = c.id AND
1241 reminder.entity_table = 'civicrm_contact' AND
1242 reminder.action_schedule_id = {$actionSchedule->id}";
1243 $addWhereClause = '';
1244 if ($addWhere) {
1245 $addWhereClause = "AND {$addWhere}";
1246 }
1247 $insertAdditionalSql ="
1248 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1249 {$addSelect}
1250 FROM ({$contactTable})
1251 LEFT JOIN {$additionReminderClause}
1252 {$addGroup}
1253 WHERE c.is_deleted = 0 AND c.is_deceased = 0
1254 {$addWhereClause}
1255
1256 AND c.id NOT IN (
1257 SELECT rem.contact_id
1258 FROM civicrm_action_log rem INNER JOIN {$mapping->entity} e ON rem.entity_id = e.id
1259 WHERE rem.action_schedule_id = {$actionSchedule->id}
1260 AND rem.entity_table = '{$mapping->entity}'
1261 )
1262 GROUP BY c.id
1263 ";
1264 CRM_Core_DAO::executeQuery($insertAdditionalSql);
1265 }
1266 // if repeat is turned ON:
1267 if ($actionSchedule->is_repeat) {
1268 $repeatEvent = ($actionSchedule->end_action == 'before' ? 'DATE_SUB' : 'DATE_ADD') . "({$dateField}, INTERVAL {$actionSchedule->end_frequency_interval} {$actionSchedule->end_frequency_unit})";
1269
1270 if ($actionSchedule->repetition_frequency_unit == 'day') {
1271 $hrs = 24 * $actionSchedule->repetition_frequency_interval;
1272 }
1273 elseif ($actionSchedule->repetition_frequency_unit == 'week') {
1274 $hrs = 24 * $actionSchedule->repetition_frequency_interval * 7;
1275 }
1276 elseif ($actionSchedule->repetition_frequency_unit == 'month') {
1277 $hrs = "24*(DATEDIFF(DATE_ADD(latest_log_time, INTERVAL 1 MONTH ), latest_log_time))";
1278 }
1279 elseif ($actionSchedule->repetition_frequency_unit == 'year') {
1280 $hrs = "24*(DATEDIFF(DATE_ADD(latest_log_time, INTERVAL 1 YEAR ), latest_log_time))";
1281 }
1282 else {
1283 $hrs = $actionSchedule->repetition_frequency_interval;
1284 }
1285
1286 // (now <= repeat_end_time )
1287 $repeatEventClause = "'{$now}' <= {$repeatEvent}";
1288 // diff(now && logged_date_time) >= repeat_interval
1289 $havingClause = "HAVING TIMEDIFF({$now}, latest_log_time) >= TIME('{$hrs}:00:00')";
1290 $groupByClause = 'GROUP BY reminder.contact_id, reminder.entity_id, reminder.entity_table';
1291 $selectClause .= ', MAX(reminder.action_date_time) as latest_log_time';
1292 //CRM-15376 - do not send our reminders if original criteria no longer applies
1293 // the first part of the startDateClause array is the earliest the reminder can be sent. If the
1294 // event (e.g membership_end_date) has changed then the reminder may no longer apply
1295 // @todo - this only handles events that get moved later. Potentially they might get moved earlier
1296 $originalEventStartDateClause = empty($startDateClause) ? '' : 'AND' . $startDateClause[0];
1297 $sqlInsertValues = "{$selectClause}
1298 {$fromClause}
1299 {$joinClause}
1300 INNER JOIN {$reminderJoinClause}
1301 {$whereClause} {$limitWhereClause} AND {$repeatEventClause} {$originalEventStartDateClause} {$notINClause}
1302 {$groupByClause}
1303 {$havingClause}";
1304
1305 $valsqlInsertValues = CRM_Core_DAO::executeQuery($sqlInsertValues, array(1 => array($actionSchedule->id, 'Integer')));
1306
1307 $arrValues = array();
1308 while ($valsqlInsertValues->fetch()) {
1309 $arrValues[] = "( {$valsqlInsertValues->contact_id}, {$valsqlInsertValues->entity_id}, '{$valsqlInsertValues->entity_table}',{$valsqlInsertValues->action_schedule_id} )";
1310 }
1311
1312 $valString = implode(',', $arrValues);
1313
1314 if ($valString) {
1315 $query = '
1316 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1317 CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer')));
1318 }
1319
1320 if ($isSendToAdditionalContacts) {
1321 $addSelect .= ', MAX(reminder.action_date_time) as latest_log_time';
1322 $sqlEndEventCheck = "
1323 SELECT * FROM {$table}
1324 {$whereClause} AND {$repeatEventClause} LIMIT 1";
1325
1326 $daoCheck = CRM_Core_DAO::executeQuery($sqlEndEventCheck);
1327 if ($daoCheck->fetch()) {
1328 $valSqlAdditionInsert = "
1329 {$addSelect}
1330 FROM {$contactTable}
1331 {$addGroup}
1332 INNER JOIN {$additionReminderClause}
1333 WHERE {$addWhere} AND c.is_deleted = 0 AND c.is_deceased = 0
1334 GROUP BY reminder.contact_id
1335 {$havingClause}
1336 ";
1337 $daoForVals = CRM_Core_DAO::executeQuery($valSqlAdditionInsert);
1338 $addValues = array();
1339 while ($daoForVals->fetch()) {
1340 $addValues[] = "( {$daoForVals->contact_id}, {$daoForVals->entity_id}, '{$daoForVals->entity_table}',{$daoForVals->action_schedule_id} )";
1341 }
1342 $valString = implode(',', $addValues);
1343
1344 if ($valString) {
1345 $query = '
1346 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1347 CRM_Core_DAO::executeQuery($query);
1348 }
1349 }
1350 }
1351 }
1352 }
1353 }
1354
1355 /**
1356 * @param $field
1357 *
1358 * @return null|string
1359 */
1360 static function permissionedRelationships($field) {
1361 $query = '
1362 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
1363 FROM civicrm_membership m
1364 LEFT JOIN civicrm_membership cm ON cm.id = m.owner_membership_id
1365 LEFT JOIN civicrm_membership_type cmt ON cmt.id = m.membership_type_id
1366 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 )
1367 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 ) )
1368 WHERE m.owner_membership_id IS NOT NULL AND
1369 ( rel.is_permission_a_b = 0 OR rel.is_permission_b_a = 0)
1370
1371 ';
1372 $excludeIds = array();
1373 $dao = CRM_Core_DAO::executeQuery($query, array());
1374 while ($dao->fetch()) {
1375 if ($dao->slave_contact == $dao->contact_id_a && $dao->is_permission_a_b == 0) {
1376 $excludeIds[] = $dao->slave_contact;
1377 }
1378 elseif ($dao->slave_contact == $dao->contact_id_b && $dao->is_permission_b_a == 0) {
1379 $excludeIds[] = $dao->slave_contact;
1380 }
1381 }
1382
1383 if (!empty($excludeIds)) {
1384 $clause = "AND {$field} NOT IN ( " .implode(', ', $excludeIds) . ' ) ';
1385 return $clause;
1386 }
1387 return NULL;
1388 }
1389
1390 /**
1391 * @param null $now
1392 * @param array $params
1393 *
1394 * @return array
1395 */
1396 static function processQueue($now = NULL, $params = array()) {
1397 $now = $now ? CRM_Utils_Time::setTime($now) : CRM_Utils_Time::getTime();
1398
1399 $mappings = self::getMapping();
1400 foreach ($mappings as $mappingID => $mapping) {
1401 self::buildRecipientContacts($mappingID, $now, $params);
1402 self::sendMailings($mappingID, $now);
1403 }
1404
1405 $result = array(
1406 'is_error' => 0,
1407 'messages' => ts('Sent all scheduled reminders successfully'),
1408 );
1409 return $result;
1410 }
1411
1412 /**
1413 * @param int $id
1414 * @param int $mappingID
1415 *
1416 * @return null|string
1417 */
1418 static function isConfigured($id, $mappingID) {
1419 $queryString = "SELECT count(id) FROM civicrm_action_schedule
1420 WHERE mapping_id = %1 AND
1421 entity_value = %2";
1422
1423 $params = array(
1424 1 => array($mappingID, 'Integer'),
1425 2 => array($id, 'Integer'),
1426 );
1427 return CRM_Core_DAO::singleValueQuery($queryString, $params);
1428 }
1429
1430 /**
1431 * @param int $mappingID
1432 * @param $recipientType
1433 *
1434 * @return array
1435 */
1436 static function getRecipientListing($mappingID, $recipientType) {
1437 $options = array();
1438 if (!$mappingID || !$recipientType) {
1439 return $options;
1440 }
1441
1442 $mapping = self::getMapping($mappingID);
1443
1444 switch ($mapping['entity']) {
1445 case 'civicrm_participant':
1446 $eventContacts = CRM_Core_OptionGroup::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name', TRUE, FALSE, 'name');
1447 if (empty($eventContacts[$recipientType])) {
1448 return $options;
1449 }
1450 if ($eventContacts[$recipientType] == 'participant_role') {
1451 $options = CRM_Event_PseudoConstant::participantRole();
1452 }
1453 break;
1454 }
1455
1456 return $options;
1457 }
1458 }