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