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