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