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