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