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