Commit | Line | Data |
---|---|---|
6a488035 TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
232624b1 | 4 | | CiviCRM version 4.4 | |
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 | |
32 | * @copyright CiviCRM LLC (c) 2004-2013 | |
33 | * $Id$ | |
34 | * | |
35 | */ | |
36 | ||
37 | /** | |
38 | * This class contains functions for managing Scheduled Reminders | |
39 | */ | |
40 | class CRM_Core_BAO_ActionSchedule extends CRM_Core_DAO_ActionSchedule { | |
41 | ||
42 | static function getMapping($id = NULL) { | |
43 | static $_action_mapping; | |
44 | ||
45 | if ($id && !is_null($_action_mapping) && isset($_action_mapping[$id])) { | |
46 | return $_action_mapping[$id]; | |
47 | } | |
48 | ||
49 | $dao = new CRM_Core_DAO_ActionMapping(); | |
50 | if ($id) { | |
51 | $dao->id = $id; | |
52 | } | |
53 | $dao->find(); | |
54 | ||
55 | $mapping = array(); | |
56 | while ($dao->fetch()) { | |
57 | $defaults = array(); | |
58 | CRM_Core_DAO::storeValues($dao, $defaults); | |
59 | $mapping[$dao->id] = $defaults; | |
60 | } | |
61 | $_action_mapping = $mapping; | |
62 | ||
63 | return $mapping; | |
64 | } | |
65 | ||
66 | /** | |
67 | * Retrieve list of selections/drop downs for Scheduled Reminder form | |
68 | * | |
69 | * @param bool $id mapping id | |
70 | * | |
71 | * @return array associated array of all the drop downs in the form | |
72 | * @static | |
73 | * @access public | |
74 | */ | |
75 | static function getSelection($id = NULL) { | |
76 | $mapping = self::getMapping($id); | |
77 | $activityStatus = CRM_Core_PseudoConstant::activityStatus(); | |
78 | $activityType = CRM_Core_PseudoConstant::activityType(FALSE) + CRM_Core_PseudoConstant::activityType(FALSE, TRUE); | |
79 | ||
80 | $participantStatus = CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label'); | |
81 | $event = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )"); | |
82 | $eventType = CRM_Event_PseudoConstant::eventType(); | |
83 | $eventTemplate = CRM_Event_PseudoConstant::eventTemplates(); | |
e7e657f0 | 84 | $autoRenew = CRM_Core_OptionGroup::values('auto_renew_options'); |
6a488035 TO |
85 | $membershipType = CRM_Member_PseudoConstant::membershipType(); |
86 | ||
87 | asort($activityType); | |
88 | ||
89 | $sel1 = $sel2 = $sel3 = $sel4 = $sel5 = array(); | |
3e315abc | 90 | $options = array( |
91 | 'manual' => ts('Choose Recipient(s)'), | |
92 | 'group' => ts('Select a Group'), | |
6a488035 TO |
93 | ); |
94 | ||
95 | $entityMapping = array(); | |
96 | $recipientMapping = array_combine(array_keys($options), array_keys($options)); | |
97 | ||
98 | if (!$id) { | |
99 | $id = 1; | |
100 | } | |
101 | ||
102 | foreach ($mapping as $value) { | |
3e315abc | 103 | $entityValue = CRM_Utils_Array::value('entity_value', $value); |
104 | $entityStatus = CRM_Utils_Array::value('entity_status', $value); | |
105 | $entityRecipient = CRM_Utils_Array::value('entity_recipient', $value); | |
106 | $valueLabel = array('- ' . strtolower(CRM_Utils_Array::value('entity_value_label', $value)) . ' -'); | |
107 | $key = CRM_Utils_Array::value('id', $value); | |
6a488035 TO |
108 | $entityMapping[$key] = CRM_Utils_Array::value('entity', $value); |
109 | ||
3e315abc | 110 | $sel1Val = NULL; |
6a488035 TO |
111 | switch ($entityValue) { |
112 | case 'activity_type': | |
113 | if ($value['entity'] == 'civicrm_activity') { | |
114 | $sel1Val = ts('Activity'); | |
115 | } | |
116 | $sel2[$key] = $valueLabel + $activityType; | |
117 | break; | |
118 | ||
119 | case 'event_type': | |
120 | if ($value['entity'] == 'civicrm_participant') { | |
121 | $sel1Val = ts('Event Type'); | |
122 | } | |
123 | $sel2[$key] = $valueLabel + $eventType; | |
124 | break; | |
125 | ||
126 | case 'event_template': | |
127 | if ($value['entity'] == 'civicrm_participant') { | |
128 | $sel1Val = ts('Event Template'); | |
129 | } | |
130 | $sel2[$key] = $valueLabel + $eventTemplate; | |
131 | break; | |
132 | ||
133 | case 'civicrm_event': | |
134 | if ($value['entity'] == 'civicrm_participant') { | |
135 | $sel1Val = ts('Event Name'); | |
136 | } | |
137 | $sel2[$key] = $valueLabel + $event; | |
138 | break; | |
139 | ||
140 | case 'civicrm_membership_type': | |
141 | if ($value['entity'] == 'civicrm_membership') { | |
142 | $sel1Val = ts('Membership'); | |
143 | } | |
144 | $sel2[$key] = $valueLabel + $membershipType; | |
145 | break; | |
146 | } | |
147 | $sel1[$key] = $sel1Val; | |
148 | ||
149 | if ($key == $id) { | |
150 | if ($startDate = CRM_Utils_Array::value('entity_date_start', $value)) { | |
151 | $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate)); | |
152 | } | |
153 | if ($endDate = CRM_Utils_Array::value('entity_date_end', $value)) { | |
154 | $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate)); | |
155 | } | |
156 | ||
157 | switch ($entityRecipient) { | |
158 | case 'activity_contacts': | |
e7e657f0 | 159 | $activityContacts = CRM_Core_OptionGroup::values('activity_contacts'); |
6a488035 | 160 | $sel5[$entityRecipient] = $activityContacts + $options; |
e7e657f0 | 161 | $recipientMapping += CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); |
6a488035 TO |
162 | break; |
163 | ||
164 | case 'event_contacts': | |
e7e657f0 | 165 | $eventContacts = CRM_Core_OptionGroup::values('event_contacts'); |
6a488035 | 166 | $sel5[$entityRecipient] = $eventContacts + $options; |
e7e657f0 | 167 | $recipientMapping += CRM_Core_OptionGroup::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name'); |
6a488035 TO |
168 | break; |
169 | ||
170 | case NULL: | |
171 | $sel5[$entityRecipient] = $options; | |
172 | break; | |
173 | } | |
174 | } | |
175 | } | |
176 | $sel3 = $sel2; | |
177 | ||
178 | foreach ($mapping as $value) { | |
179 | $entityStatus = CRM_Utils_Array::value('entity_status', $value); | |
3e315abc | 180 | $statusLabel = array('- ' . strtolower(CRM_Utils_Array::value('entity_status_label', $value)) . ' -'); |
181 | $id = CRM_Utils_Array::value('id', $value); | |
6a488035 TO |
182 | |
183 | switch ($entityStatus) { | |
184 | case 'activity_status': | |
185 | foreach ($sel3[$id] as $kkey => & $vval) { | |
186 | $vval = $statusLabel + $activityStatus; | |
187 | } | |
188 | break; | |
189 | ||
190 | case 'civicrm_participant_status_type': | |
191 | foreach ($sel3[$id] as $kkey => & $vval) { | |
192 | $vval = $statusLabel + $participantStatus; | |
193 | } | |
194 | break; | |
195 | ||
196 | case 'auto_renew_options': | |
197 | foreach ($sel3[$id] as $kkey => & $vval) { | |
198 | $auto = 0; | |
199 | if ($kkey) { | |
200 | $auto = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $kkey, 'auto_renew'); | |
201 | } | |
202 | if ( $auto ) { | |
203 | $vval = $statusLabel + $autoRenew; | |
204 | } | |
205 | else { | |
206 | $vval = $statusLabel; | |
207 | } | |
208 | } | |
209 | break; | |
210 | ||
211 | case '': | |
212 | $sel3[$id] = ''; | |
213 | break; | |
214 | ||
215 | } | |
216 | } | |
6a488035 TO |
217 | return array( |
218 | 'sel1' => $sel1, | |
219 | 'sel2' => $sel2, | |
220 | 'sel3' => $sel3, | |
221 | 'sel4' => $sel4, | |
222 | 'sel5' => $sel5, | |
223 | 'entityMapping' => $entityMapping, | |
224 | 'recipientMapping' => $recipientMapping, | |
225 | ); | |
226 | } | |
227 | ||
228 | static function getSelection1($id = NULL) { | |
229 | $mapping = self::getMapping($id); | |
3e315abc | 230 | $sel4 = $sel5 = array(); |
231 | $options = array( | |
232 | 'manual' => ts('Choose Recipient(s)'), | |
233 | 'group' => ts('Select a Group'), | |
6a488035 TO |
234 | ); |
235 | ||
236 | $recipientMapping = array_combine(array_keys($options), array_keys($options)); | |
237 | ||
238 | foreach ($mapping as $value) { | |
239 | $entityRecipient = CRM_Utils_Array::value('entity_recipient', $value); | |
240 | $key = CRM_Utils_Array::value('id', $value); | |
241 | ||
242 | if ($startDate = CRM_Utils_Array::value('entity_date_start', $value)) { | |
243 | $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate)); | |
244 | } | |
245 | if ($endDate = CRM_Utils_Array::value('entity_date_end', $value)) { | |
246 | $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate)); | |
247 | } | |
248 | ||
249 | switch ($entityRecipient) { | |
250 | case 'activity_contacts': | |
e7e657f0 | 251 | $activityContacts = CRM_Core_OptionGroup::values('activity_contacts'); |
6a488035 | 252 | $sel5[$id] = $activityContacts + $options; |
e7e657f0 | 253 | $recipientMapping += CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); |
6a488035 TO |
254 | break; |
255 | ||
256 | case 'event_contacts': | |
e7e657f0 | 257 | $eventContacts = CRM_Core_OptionGroup::values('event_contacts'); |
6a488035 | 258 | $sel5[$id] = $eventContacts + $options; |
e7e657f0 | 259 | $recipientMapping += CRM_Core_OptionGroup::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name'); |
6a488035 TO |
260 | break; |
261 | ||
262 | case NULL: | |
263 | $sel5[$id] = $options; | |
264 | break; | |
265 | } | |
266 | } | |
267 | ||
268 | return array( | |
269 | 'sel4' => $sel4, | |
270 | 'sel5' => $sel5[$id], | |
271 | 'recipientMapping' => $recipientMapping, | |
272 | ); | |
273 | } | |
274 | ||
275 | /** | |
276 | * Retrieve list of Scheduled Reminders | |
277 | * | |
278 | * @param bool $namesOnly return simple list of names | |
279 | * | |
280 | * @return array (reference) reminder list | |
281 | * @static | |
282 | * @access public | |
283 | */ | |
284 | static function &getList($namesOnly = FALSE, $entityValue = NULL, $id = NULL) { | |
285 | $activity_type = CRM_Core_PseudoConstant::activityType(FALSE) + CRM_Core_PseudoConstant::activityType(FALSE, TRUE); | |
286 | $activity_status = CRM_Core_PseudoConstant::activityStatus(); | |
287 | ||
288 | $event_type = CRM_Event_PseudoConstant::eventType(); | |
289 | $civicrm_event = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )"); | |
290 | $civicrm_participant_status_type = CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label'); | |
291 | $event_template = CRM_Event_PseudoConstant::eventTemplates(); | |
292 | ||
e7e657f0 | 293 | $auto_renew_options = CRM_Core_OptionGroup::values('auto_renew_options'); |
6a488035 TO |
294 | $civicrm_membership_type = CRM_Member_PseudoConstant::membershipType(); |
295 | ||
296 | asort($activity_type); | |
297 | $entity = array( | |
298 | 'civicrm_activity' => 'Activity', | |
299 | 'civicrm_participant' => 'Event', | |
300 | 'civicrm_membership' => 'Member', | |
301 | ); | |
302 | ||
303 | $query = " | |
304 | SELECT | |
305 | title, | |
306 | cam.entity, | |
307 | cas.id as id, | |
308 | cam.entity_value as entityValue, | |
309 | cas.entity_value as entityValueIds, | |
310 | cam.entity_status as entityStatus, | |
311 | cas.entity_status as entityStatusIds, | |
312 | cas.start_action_date as entityDate, | |
313 | cas.start_action_offset, | |
314 | cas.start_action_unit, | |
315 | cas.start_action_condition, | |
316 | cas.absolute_date, | |
317 | is_repeat, | |
318 | is_active | |
319 | ||
320 | FROM civicrm_action_schedule cas | |
321 | LEFT JOIN civicrm_action_mapping cam ON (cam.id = cas.mapping_id) | |
322 | "; | |
323 | $params = CRM_Core_DAO::$_nullArray; | |
324 | ||
325 | if ($entityValue and $id) { | |
326 | $where = " | |
327 | WHERE cas.entity_value = $id AND | |
328 | cam.entity_value = '$entityValue'"; | |
329 | ||
330 | $query .= $where; | |
331 | ||
3e315abc | 332 | $params = array( |
333 | 1 => array($id, 'Integer'), | |
334 | 2 => array($entityValue, 'String'), | |
6a488035 TO |
335 | ); |
336 | } | |
337 | ||
338 | $dao = CRM_Core_DAO::executeQuery($query); | |
339 | while ($dao->fetch()) { | |
340 | $list[$dao->id]['id'] = $dao->id; | |
341 | $list[$dao->id]['title'] = $dao->title; | |
342 | $list[$dao->id]['start_action_offset'] = $dao->start_action_offset; | |
343 | $list[$dao->id]['start_action_unit'] = $dao->start_action_unit; | |
344 | $list[$dao->id]['start_action_condition'] = $dao->start_action_condition; | |
345 | $list[$dao->id]['entityDate'] = ucwords(str_replace('_', ' ', $dao->entityDate)); | |
346 | $list[$dao->id]['absolute_date'] = $dao->absolute_date; | |
347 | ||
348 | $status = $dao->entityStatus; | |
349 | $statusArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $dao->entityStatusIds); | |
350 | foreach ($statusArray as & $s) { | |
351 | $s = CRM_Utils_Array::value($s, $$status); | |
352 | } | |
353 | $statusIds = implode(', ', $statusArray); | |
354 | ||
355 | $value = $dao->entityValue; | |
356 | $valueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $dao->entityValueIds); | |
357 | foreach ($valueArray as & $v) { | |
358 | $v = CRM_Utils_Array::value($v, $$value); | |
359 | } | |
360 | $valueIds = implode(', ', $valueArray); | |
361 | $list[$dao->id]['entity'] = $entity[$dao->entity]; | |
362 | $list[$dao->id]['value'] = $valueIds; | |
363 | $list[$dao->id]['status'] = $statusIds; | |
364 | $list[$dao->id]['is_repeat'] = $dao->is_repeat; | |
365 | $list[$dao->id]['is_active'] = $dao->is_active; | |
366 | } | |
367 | ||
368 | return $list; | |
369 | } | |
370 | ||
371 | static function sendReminder($contactId, $email, $scheduleID, $from, $tokenParams) { | |
372 | ||
373 | $schedule = new CRM_Core_DAO_ActionSchedule(); | |
374 | $schedule->id = $scheduleID; | |
375 | ||
376 | $domain = CRM_Core_BAO_Domain::getDomain(); | |
377 | $result = NULL; | |
378 | $hookTokens = array(); | |
379 | ||
380 | if ($schedule->find(TRUE)) { | |
381 | $body_text = $schedule->body_text; | |
382 | $body_html = $schedule->body_html; | |
383 | $body_subject = $schedule->subject; | |
384 | if (!$body_text) { | |
385 | $body_text = CRM_Utils_String::htmlToText($body_html); | |
386 | } | |
387 | ||
388 | $params = array(array('contact_id', '=', $contactId, 0, 0)); | |
389 | list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($params); | |
390 | ||
391 | //CRM-4524 | |
392 | $contact = reset($contact); | |
393 | ||
394 | if (!$contact || is_a($contact, 'CRM_Core_Error')) { | |
395 | return NULL; | |
396 | } | |
397 | ||
398 | // merge activity tokens with contact array | |
399 | $contact = array_merge($contact, $tokenParams); | |
400 | ||
401 | //CRM-5734 | |
402 | CRM_Utils_Hook::tokenValues($contact, $contactId); | |
403 | ||
404 | CRM_Utils_Hook::tokens($hookTokens); | |
405 | $categories = array_keys($hookTokens); | |
406 | ||
407 | $type = array('html', 'text'); | |
408 | ||
409 | foreach ($type as $key => $value) { | |
410 | $dummy_mail = new CRM_Mailing_BAO_Mailing(); | |
411 | $bodyType = "body_{$value}"; | |
412 | $dummy_mail->$bodyType = $$bodyType; | |
413 | $tokens = $dummy_mail->getTokens(); | |
414 | ||
415 | if ($$bodyType) { | |
416 | CRM_Utils_Token::replaceGreetingTokens($$bodyType, NULL, $contact['contact_id']); | |
417 | $$bodyType = CRM_Utils_Token::replaceDomainTokens($$bodyType, $domain, TRUE, $tokens[$value], TRUE); | |
418 | $$bodyType = CRM_Utils_Token::replaceContactTokens($$bodyType, $contact, FALSE, $tokens[$value], FALSE, TRUE); | |
419 | $$bodyType = CRM_Utils_Token::replaceComponentTokens($$bodyType, $contact, $tokens[$value], TRUE, FALSE); | |
420 | $$bodyType = CRM_Utils_Token::replaceHookTokens($$bodyType, $contact, $categories, TRUE); | |
421 | } | |
422 | } | |
423 | $html = $body_html; | |
424 | $text = $body_text; | |
425 | ||
4ee279f4 | 426 | $smarty = CRM_Core_Smarty::singleton(); |
427 | foreach (array( | |
428 | 'text', 'html') as $elem) { | |
429 | $$elem = $smarty->fetch("string:{$$elem}"); | |
430 | } | |
431 | ||
6a488035 TO |
432 | $matches = array(); |
433 | preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/', | |
434 | $body_subject, | |
435 | $matches, | |
436 | PREG_PATTERN_ORDER | |
437 | ); | |
438 | ||
439 | $subjectToken = NULL; | |
440 | if ($matches[1]) { | |
441 | foreach ($matches[1] as $token) { | |
442 | list($type, $name) = preg_split('/\./', $token, 2); | |
443 | if ($name) { | |
444 | if (!isset($subjectToken['contact'])) { | |
445 | $subjectToken['contact'] = array(); | |
446 | } | |
447 | $subjectToken['contact'][] = $name; | |
448 | } | |
449 | } | |
450 | } | |
451 | ||
452 | $messageSubject = CRM_Utils_Token::replaceContactTokens($body_subject, $contact, FALSE, $subjectToken); | |
453 | $messageSubject = CRM_Utils_Token::replaceDomainTokens($messageSubject, $domain, TRUE, $tokens[$value]); | |
454 | $messageSubject = CRM_Utils_Token::replaceComponentTokens($messageSubject, $contact, $tokens[$value], TRUE); | |
455 | $messageSubject = CRM_Utils_Token::replaceHookTokens($messageSubject, $contact, $categories, TRUE); | |
456 | ||
4ee279f4 | 457 | $messageSubject = $smarty->fetch("string:{$messageSubject}"); |
458 | ||
6a488035 TO |
459 | // set up the parameters for CRM_Utils_Mail::send |
460 | $mailParams = array( | |
461 | 'groupName' => 'Scheduled Reminder Sender', | |
462 | 'from' => $from, | |
463 | 'toName' => $contact['display_name'], | |
464 | 'toEmail' => $email, | |
465 | 'subject' => $messageSubject, | |
24f14405 E |
466 | 'entity' => 'action_schedule', |
467 | 'entity_id' => $scheduleID, | |
6a488035 TO |
468 | ); |
469 | ||
470 | if (!$html || $contact['preferred_mail_format'] == 'Text' || | |
471 | $contact['preferred_mail_format'] == 'Both' | |
472 | ) { | |
473 | // render the & entities in text mode, so that the links work | |
474 | $mailParams['text'] = str_replace('&', '&', $text); | |
475 | } | |
476 | if ($html && ($contact['preferred_mail_format'] == 'HTML' || | |
477 | $contact['preferred_mail_format'] == 'Both' | |
478 | )) { | |
479 | $mailParams['html'] = $html; | |
480 | } | |
481 | ||
482 | $result = CRM_Utils_Mail::send($mailParams); | |
483 | } | |
484 | $schedule->free(); | |
485 | ||
486 | return $result; | |
487 | } | |
488 | ||
489 | /** | |
490 | * Function to add the schedules reminders in the db | |
491 | * | |
492 | * @param array $params (reference ) an assoc array of name/value pairs | |
493 | * @param array $ids the array that holds all the db ids | |
494 | * | |
495 | * @return object CRM_Core_DAO_ActionSchedule | |
496 | * @access public | |
497 | * @static | |
498 | * | |
499 | */ | |
5284dd80 | 500 | static function add(&$params, $ids = array()) { |
6a488035 TO |
501 | $actionSchedule = new CRM_Core_DAO_ActionSchedule(); |
502 | $actionSchedule->copyValues($params); | |
503 | ||
504 | return $actionSchedule->save(); | |
505 | } | |
506 | ||
507 | /** | |
508 | * Takes a bunch of params that are needed to match certain criteria and | |
509 | * retrieves the relevant objects. It also stores all the retrieved | |
510 | * values in the default array | |
511 | * | |
512 | * @param array $params (reference ) an assoc array of name/value pairs | |
513 | * @param array $values (reference ) an assoc array to hold the flattened values | |
514 | * | |
515 | * @return object CRM_Core_DAO_ActionSchedule object on success, null otherwise | |
516 | * @access public | |
517 | * @static | |
518 | */ | |
519 | static function retrieve(&$params, &$values) { | |
520 | if (empty($params)) { | |
521 | return NULL; | |
522 | } | |
523 | $actionSchedule = new CRM_Core_DAO_ActionSchedule(); | |
524 | ||
525 | $actionSchedule->copyValues($params); | |
526 | ||
527 | if ($actionSchedule->find(TRUE)) { | |
528 | $ids['actionSchedule'] = $actionSchedule->id; | |
529 | ||
530 | CRM_Core_DAO::storeValues($actionSchedule, $values); | |
531 | ||
532 | return $actionSchedule; | |
533 | } | |
534 | return NULL; | |
535 | } | |
536 | ||
537 | /** | |
538 | * Function to delete a Reminder | |
539 | * | |
540 | * @param int $id ID of the Reminder to be deleted. | |
541 | * | |
542 | * @access public | |
543 | * @static | |
544 | */ | |
545 | static function del($id) { | |
546 | if ($id) { | |
547 | $dao = new CRM_Core_DAO_ActionSchedule(); | |
548 | $dao->id = $id; | |
549 | if ($dao->find(TRUE)) { | |
550 | $dao->delete(); | |
551 | return; | |
552 | } | |
553 | } | |
554 | CRM_Core_Error::fatal(ts('Invalid value passed to delete function.')); | |
555 | } | |
556 | ||
557 | /** | |
558 | * update the is_active flag in the db | |
559 | * | |
560 | * @param int $id id of the database record | |
561 | * @param boolean $is_active value we want to set the is_active field | |
562 | * | |
563 | * @return Object DAO object on success, null otherwise | |
564 | * @static | |
565 | */ | |
566 | static function setIsActive($id, $is_active) { | |
567 | return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active); | |
568 | } | |
569 | ||
570 | static function sendMailings($mappingID, $now) { | |
571 | $domainValues = CRM_Core_BAO_Domain::getNameAndEmail(); | |
572 | $fromEmailAddress = "$domainValues[0] <$domainValues[1]>"; | |
573 | ||
574 | $mapping = new CRM_Core_DAO_ActionMapping(); | |
575 | $mapping->id = $mappingID; | |
576 | $mapping->find(TRUE); | |
577 | ||
578 | $actionSchedule = new CRM_Core_DAO_ActionSchedule(); | |
579 | $actionSchedule->mapping_id = $mappingID; | |
580 | $actionSchedule->is_active = 1; | |
581 | $actionSchedule->find(FALSE); | |
582 | ||
583 | $tokenFields = array(); | |
584 | $session = CRM_Core_Session::singleton(); | |
585 | ||
586 | while ($actionSchedule->fetch()) { | |
bb56ad3d | 587 | $extraSelect = $extraJoin = $extraWhere = $extraOn = ''; |
6a488035 TO |
588 | |
589 | if ($actionSchedule->record_activity) { | |
590 | if ($mapping->entity == 'civicrm_membership') { | |
591 | $activityTypeID = | |
592 | CRM_Core_OptionGroup::getValue('activity_type', 'Membership Renewal Reminder', 'name'); | |
593 | } | |
594 | else { | |
595 | $activityTypeID = | |
596 | CRM_Core_OptionGroup::getValue('activity_type', 'Reminder Sent', 'name'); | |
597 | } | |
598 | ||
599 | $activityStatusID = | |
600 | CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'); | |
601 | } | |
602 | ||
603 | if ($mapping->entity == 'civicrm_activity') { | |
604 | $tokenEntity = 'activity'; | |
605 | $tokenFields = array('activity_id', 'activity_type', 'subject', 'details', 'activity_date_time'); | |
606 | $extraSelect = ', ov.label as activity_type, e.id as activity_id'; | |
a4b156a7 PJ |
607 | $extraJoin = " |
608 | INNER JOIN civicrm_option_group og ON og.name = 'activity_type' | |
6a488035 | 609 | INNER JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id"; |
7188a78d | 610 | $extraOn = ' AND e.is_current_revision = 1 AND e.is_deleted = 0 '; |
a4b156a7 PJ |
611 | if ($actionSchedule->limit_to == 0) { |
612 | $extraJoin = " | |
613 | LEFT JOIN civicrm_option_group og ON og.name = 'activity_type' | |
614 | LEFT JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id"; | |
a4b156a7 | 615 | } |
6a488035 TO |
616 | } |
617 | ||
618 | if ($mapping->entity == 'civicrm_participant') { | |
619 | $tokenEntity = 'event'; | |
620 | $tokenFields = array('event_type', 'title', 'event_id', 'start_date', 'end_date', 'summary', 'description', 'location', 'info_url', 'registration_url', 'fee_amount', 'contact_email', 'contact_phone'); | |
621 | $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 '; | |
622 | ||
623 | $extraJoin = " | |
624 | INNER JOIN civicrm_event ev ON e.event_id = ev.id | |
625 | INNER JOIN civicrm_option_group og ON og.name = 'event_type' | |
626 | INNER JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id | |
627 | LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id | |
628 | LEFT JOIN civicrm_address address ON address.id = lb.address_id | |
629 | LEFT JOIN civicrm_email email ON email.id = lb.email_id | |
630 | LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id | |
631 | "; | |
a4b156a7 PJ |
632 | if ($actionSchedule->limit_to == 0) { |
633 | $extraJoin = " | |
634 | LEFT JOIN civicrm_event ev ON e.event_id = ev.id | |
635 | LEFT JOIN civicrm_option_group og ON og.name = 'event_type' | |
636 | LEFT JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id | |
637 | LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id | |
638 | LEFT JOIN civicrm_address address ON address.id = lb.address_id | |
639 | LEFT JOIN civicrm_email email ON email.id = lb.email_id | |
640 | LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id | |
641 | "; | |
642 | } | |
6a488035 TO |
643 | } |
644 | ||
645 | if ($mapping->entity == 'civicrm_membership') { | |
646 | $tokenEntity = 'membership'; | |
647 | $tokenFields = array('fee', 'id', 'join_date', 'start_date', 'end_date', 'status', 'type'); | |
648 | $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'; | |
649 | $extraJoin = ' | |
650 | INNER JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id | |
651 | INNER JOIN civicrm_membership_status ms ON e.status_id = ms.id'; | |
a4b156a7 PJ |
652 | |
653 | if ($actionSchedule->limit_to == 0) { | |
654 | $extraJoin = ' | |
655 | LEFT JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id | |
656 | LEFT JOIN civicrm_membership_status ms ON e.status_id = ms.id'; | |
657 | } | |
658 | } | |
659 | ||
660 | $entityJoinClause = "INNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id"; | |
661 | if ($actionSchedule->limit_to == 0) { | |
662 | $entityJoinClause = "LEFT JOIN {$mapping->entity} e ON e.id = reminder.entity_id"; | |
663 | $extraWhere .= " AND (e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact')"; | |
6a488035 | 664 | } |
bb56ad3d | 665 | $entityJoinClause .= $extraOn; |
6a488035 TO |
666 | |
667 | $query = " | |
a4b156a7 | 668 | SELECT reminder.id as reminderID, reminder.contact_id as contactID, reminder.*, e.id as entityID, e.* {$extraSelect} |
6a488035 | 669 | FROM civicrm_action_log reminder |
a4b156a7 | 670 | {$entityJoinClause} |
6a488035 TO |
671 | {$extraJoin} |
672 | WHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL | |
673 | {$extraWhere}"; | |
674 | ||
675 | $dao = CRM_Core_DAO::executeQuery($query, | |
3e315abc | 676 | array(1 => array($actionSchedule->id, 'Integer')) |
6a488035 TO |
677 | ); |
678 | ||
679 | while ($dao->fetch()) { | |
680 | $entityTokenParams = array(); | |
681 | foreach ($tokenFields as $field) { | |
682 | if ($field == 'location') { | |
683 | $loc = array(); | |
684 | $stateProvince = CRM_Core_PseudoConstant::stateProvince(); | |
685 | $loc['street_address'] = $dao->street_address; | |
686 | $loc['city'] = $dao->city; | |
a124ebd4 | 687 | $loc['state_province'] = CRM_Utils_Array::value($dao->state_province_id, $stateProvince); |
6a488035 TO |
688 | $loc['postal_code'] = $dao->postal_code; |
689 | $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address::format($loc); | |
690 | } | |
691 | elseif ($field == 'info_url') { | |
692 | $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE); | |
693 | } | |
694 | elseif ($field == 'registration_url') { | |
695 | $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE); | |
696 | } | |
697 | elseif (in_array($field, array('start_date','end_date','join_date','activity_date_time'))) { | |
698 | $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date::customFormat($dao->$field); | |
699 | } | |
700 | else { | |
701 | $entityTokenParams["{$tokenEntity}." . $field] = $dao->$field; | |
702 | } | |
703 | } | |
704 | ||
705 | $isError = 0; | |
706 | $errorMsg = ''; | |
a4b156a7 | 707 | $toEmail = CRM_Contact_BAO_Contact::getPrimaryEmail($dao->contactID); |
6a488035 TO |
708 | if ($toEmail) { |
709 | $result = | |
710 | CRM_Core_BAO_ActionSchedule::sendReminder( | |
a4b156a7 | 711 | $dao->contactID, |
6a488035 TO |
712 | $toEmail, |
713 | $actionSchedule->id, | |
714 | $fromEmailAddress, | |
715 | $entityTokenParams | |
716 | ); | |
717 | ||
718 | if (!$result || is_a($result, 'PEAR_Error')) { | |
719 | // we could not send an email, for now we ignore, CRM-3406 | |
720 | $isError = 1; | |
721 | } | |
722 | } | |
723 | else { | |
724 | $isError = 1; | |
725 | $errorMsg = "Couldn\'t find recipient\'s email address."; | |
726 | } | |
727 | ||
728 | // update action log record | |
729 | $logParams = array( | |
730 | 'id' => $dao->reminderID, | |
731 | 'is_error' => $isError, | |
732 | 'message' => $errorMsg ? $errorMsg : "null", | |
733 | 'action_date_time' => $now, | |
734 | ); | |
735 | CRM_Core_BAO_ActionLog::create($logParams); | |
736 | ||
737 | // insert activity log record if needed | |
738 | if ($actionSchedule->record_activity) { | |
739 | $activityParams = array( | |
740 | 'subject' => $actionSchedule->title, | |
741 | 'details' => $actionSchedule->body_html, | |
b319d00a | 742 | 'source_contact_id' => |
a4b156a7 PJ |
743 | $session->get('userID') ? $session->get('userID') : $dao->contactID, |
744 | 'target_contact_id' => $dao->contactID, | |
6a488035 TO |
745 | 'activity_date_time' => date('YmdHis'), |
746 | 'status_id' => $activityStatusID, | |
747 | 'activity_type_id' => $activityTypeID, | |
748 | 'source_record_id' => $dao->entityID, | |
749 | ); | |
750 | $activity = CRM_Activity_BAO_Activity::create($activityParams); | |
751 | } | |
752 | } | |
753 | ||
754 | $dao->free(); | |
755 | } | |
756 | } | |
757 | ||
758 | static function buildRecipientContacts($mappingID, $now) { | |
759 | $actionSchedule = new CRM_Core_DAO_ActionSchedule(); | |
760 | $actionSchedule->mapping_id = $mappingID; | |
761 | $actionSchedule->is_active = 1; | |
762 | $actionSchedule->find(); | |
763 | ||
764 | while ($actionSchedule->fetch()) { | |
765 | $mapping = new CRM_Core_DAO_ActionMapping(); | |
766 | $mapping->id = $mappingID; | |
767 | $mapping->find(TRUE); | |
768 | ||
6d98dbc7 PJ |
769 | // note: $where - this filtering applies for both |
770 | // 'limit to' and 'addition to' options | |
771 | // $limitWhere - this filtering applies only for | |
772 | // 'limit to' option | |
773 | $select = $join = $where = $limitWhere = array(); | |
3e315abc | 774 | $limitTo = $actionSchedule->limit_to; |
6a488035 | 775 | $value = explode(CRM_Core_DAO::VALUE_SEPARATOR, |
3e315abc | 776 | trim($actionSchedule->entity_value, CRM_Core_DAO::VALUE_SEPARATOR) |
6a488035 TO |
777 | ); |
778 | $value = implode(',', $value); | |
779 | ||
780 | $status = explode(CRM_Core_DAO::VALUE_SEPARATOR, | |
3e315abc | 781 | trim($actionSchedule->entity_status, CRM_Core_DAO::VALUE_SEPARATOR) |
6a488035 TO |
782 | ); |
783 | $status = implode(',', $status); | |
784 | ||
785 | if (!CRM_Utils_System::isNull($mapping->entity_recipient)) { | |
40f2fee3 | 786 | $recipientOptions = CRM_Core_OptionGroup::values($mapping->entity_recipient, FALSE, FALSE, FALSE, NULL, 'name'); |
6a488035 TO |
787 | } |
788 | $from = "{$mapping->entity} e"; | |
789 | ||
790 | if ($mapping->entity == 'civicrm_activity') { | |
00b1b9f1 | 791 | $contactField = 'r.contact_id'; |
6cb6ba4c | 792 | $table = 'civicrm_activity e'; |
e7e657f0 | 793 | $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); |
9e74e3ce | 794 | $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts); |
795 | $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts); | |
796 | $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts); | |
b319d00a | 797 | |
bb56ad3d PJ |
798 | if ($limitTo == 0) { |
799 | // including the activity target contacts if 'in addition' is defined | |
800 | $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}"; | |
801 | } | |
802 | else { | |
803 | switch (CRM_Utils_Array::value($actionSchedule->recipient, $recipientOptions)) { | |
804 | case 'Activity Assignees': | |
805 | $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$assigneeID}"; | |
806 | break; | |
6a488035 | 807 | |
bb56ad3d PJ |
808 | case 'Activity Source': |
809 | $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$sourceID}"; | |
810 | break; | |
6a488035 | 811 | |
bb56ad3d PJ |
812 | default: |
813 | case 'Activity Targets': | |
814 | $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}"; | |
815 | break; | |
816 | } | |
6a488035 TO |
817 | } |
818 | // build where clause | |
819 | if (!empty($value)) { | |
820 | $where[] = "e.activity_type_id IN ({$value})"; | |
821 | } | |
822 | else { | |
823 | $where[] = "e.activity_type_id IS NULL"; | |
824 | } | |
825 | if (!empty($status)) { | |
826 | $where[] = "e.status_id IN ({$status})"; | |
827 | } | |
828 | $where[] = ' e.is_current_revision = 1 '; | |
829 | $where[] = ' e.is_deleted = 0 '; | |
830 | ||
831 | $dateField = 'e.activity_date_time'; | |
832 | } | |
833 | ||
834 | if ($mapping->entity == 'civicrm_participant') { | |
6cb6ba4c | 835 | $table = 'civicrm_event r'; |
6a488035 TO |
836 | $contactField = 'e.contact_id'; |
837 | $join[] = 'INNER JOIN civicrm_event r ON e.event_id = r.id'; | |
bb56ad3d | 838 | if ($actionSchedule->recipient_listing && $limitTo) { |
6a488035 | 839 | $rList = explode(CRM_Core_DAO::VALUE_SEPARATOR, |
3e315abc | 840 | trim($actionSchedule->recipient_listing, CRM_Core_DAO::VALUE_SEPARATOR) |
6a488035 TO |
841 | ); |
842 | $rList = implode(',', $rList); | |
843 | ||
844 | switch ($recipientOptions[$actionSchedule->recipient]) { | |
40f2fee3 | 845 | case 'participant_role': |
6a488035 TO |
846 | $where[] = "e.role_id IN ({$rList})"; |
847 | break; | |
848 | ||
849 | default: | |
850 | break; | |
851 | } | |
852 | } | |
853 | ||
854 | // build where clause | |
855 | if (!empty($value)) { | |
856 | $where[] = ($mapping->entity_value == 'event_type') ? "r.event_type_id IN ({$value})" : "r.id IN ({$value})"; | |
857 | } | |
858 | else { | |
859 | $where[] = ($mapping->entity_value == 'event_type') ? "r.event_type_id IS NULL" : "r.id IS NULL"; | |
860 | } | |
861 | ||
6d98dbc7 PJ |
862 | // participant status criteria not to be implemented |
863 | // for additional recipients | |
6a488035 | 864 | if (!empty($status)) { |
6d98dbc7 | 865 | $limitWhere[] = "e.status_id IN ({$status})"; |
6a488035 TO |
866 | } |
867 | ||
868 | $where[] = 'r.is_active = 1'; | |
869 | $where[] = 'r.is_template = 0'; | |
870 | $dateField = str_replace('event_', 'r.', $actionSchedule->start_action_date); | |
871 | } | |
872 | ||
873 | $notINClause = ''; | |
874 | if ($mapping->entity == 'civicrm_membership') { | |
875 | $contactField = 'e.contact_id'; | |
6cb6ba4c | 876 | $table = 'civicrm_membership e'; |
6a488035 TO |
877 | // build where clause |
878 | if ( $status == 2 ) { | |
879 | //auto-renew memberships | |
880 | $where[] = "e.contribution_recur_id IS NOT NULL "; | |
881 | } | |
882 | elseif ( $status == 1 ) { | |
883 | $where[] = "e.contribution_recur_id IS NULL "; | |
884 | } | |
885 | ||
886 | // build where clause | |
887 | if (!empty($value)) { | |
888 | $where[] = "e.membership_type_id IN ({$value})"; | |
889 | } | |
890 | else { | |
891 | $where[] = "e.membership_type_id IS NULL"; | |
892 | } | |
893 | ||
eec002d2 | 894 | $where[] = "( e.is_override IS NULL OR e.is_override = 0 )"; |
6a488035 TO |
895 | $dateField = str_replace('membership_', 'e.', $actionSchedule->start_action_date); |
896 | $notINClause = self::permissionedRelationships($contactField); | |
b319d00a | 897 | |
7e9f2e18 | 898 | $membershipStatus = CRM_Member_PseudoConstant::membershipStatus(NULL, "(is_current_member = 1 OR name = 'Expired')", 'id'); |
b1998d9c | 899 | $mStatus = implode (',', $membershipStatus); |
ed920eb1 | 900 | $where[] = "e.status_id IN ({$mStatus})"; |
6a488035 | 901 | } |
6d98dbc7 | 902 | |
f10c69fa DL |
903 | // CRM-13577 Introduce Smart Groups Handling |
904 | if ($actionSchedule->group_id) { | |
905 | ||
906 | // Need to check if its a smart group or not | |
907 | // Then decide which table to join onto the query | |
2dd1b730 | 908 | $group = CRM_Contact_DAO_Group::getTableName(); |
f10c69fa DL |
909 | |
910 | // Get the group information | |
911 | $sql = " | |
912 | SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children | |
913 | FROM $group | |
914 | WHERE $group.id = {$actionSchedule->group_id} | |
915 | "; | |
916 | ||
917 | $groupDAO = CRM_Core_DAO::executeQuery($sql); | |
918 | $isSmartGroup = FALSE; | |
919 | if ( | |
920 | $groupDAO->fetch() && | |
921 | !empty($groupDAO->saved_search_id) | |
922 | ) { | |
923 | // Check that the group is in place in the cache and up to date | |
924 | CRM_Contact_BAO_GroupContactCache::check($actionSchedule->group_id); | |
925 | // Set smart group flag | |
926 | $isSmartGroup = TRUE; | |
927 | } | |
928 | } | |
929 | // CRM-13577 End Introduce Smart Groups Handling | |
930 | ||
6cb6ba4c | 931 | if ($limitTo) { |
932 | if ($actionSchedule->group_id) { | |
f10c69fa DL |
933 | // CRM-13577 If smart group then use Cache table |
934 | if ($isSmartGroup) { | |
935 | $join[] = "INNER JOIN civicrm_group_contact_cache grp ON {$contactField} = grp.contact_id"; | |
936 | $where[] = "grp.group_id IN ({$actionSchedule->group_id})"; | |
937 | } else { | |
938 | $join[] = "INNER JOIN civicrm_group_contact grp ON {$contactField} = grp.contact_id AND grp.status = 'Added'"; | |
939 | $where[] = "grp.group_id IN ({$actionSchedule->group_id})"; | |
940 | } | |
6cb6ba4c | 941 | } |
942 | elseif (!empty($actionSchedule->recipient_manual)) { | |
943 | $rList = CRM_Utils_Type::escape($actionSchedule->recipient_manual, 'String'); | |
944 | $where[] = "{$contactField} IN ({$rList})"; | |
945 | } | |
6a488035 | 946 | } |
6cb6ba4c | 947 | else { |
a4b156a7 | 948 | $addGroup = $addWhere = ''; |
6cb6ba4c | 949 | if ($actionSchedule->group_id) { |
f10c69fa DL |
950 | // CRM-13577 If smart group then use Cache table |
951 | if ($isSmartGroup) { | |
952 | $addGroup = " INNER JOIN civicrm_group_contact_cache grp ON c.id = grp.contact_id"; | |
953 | $addWhere = " grp.group_id IN ({$actionSchedule->group_id})"; | |
954 | } else { | |
955 | $addGroup = " INNER JOIN civicrm_group_contact grp ON c.id = grp.contact_id AND grp.status = 'Added'"; | |
956 | $addWhere = " grp.group_id IN ({$actionSchedule->group_id})"; | |
957 | } | |
6cb6ba4c | 958 | } |
959 | if (!empty($actionSchedule->recipient_manual)) { | |
960 | $rList = CRM_Utils_Type::escape($actionSchedule->recipient_manual, 'String'); | |
961 | $addWhere = "c.id IN ({$rList})"; | |
962 | } | |
6a488035 | 963 | } |
6d98dbc7 | 964 | |
3e315abc | 965 | $select[] = "{$contactField} as contact_id"; |
966 | $select[] = 'e.id as entity_id'; | |
967 | $select[] = "'{$mapping->entity}' as entity_table"; | |
968 | $select[] = "{$actionSchedule->id} as action_schedule_id"; | |
6a488035 TO |
969 | $reminderJoinClause = "civicrm_action_log reminder ON reminder.contact_id = {$contactField} AND |
970 | reminder.entity_id = e.id AND | |
971 | reminder.entity_table = '{$mapping->entity}' AND | |
972 | reminder.action_schedule_id = %1"; | |
973 | ||
ed920eb1 | 974 | $join[] = "INNER JOIN civicrm_contact c ON c.id = {$contactField} AND c.is_deleted = 0 AND c.is_deceased = 0 "; |
6a488035 TO |
975 | |
976 | if ($actionSchedule->start_action_date) { | |
3e315abc | 977 | $startDateClause = array(); |
978 | $op = ($actionSchedule->start_action_condition == 'before' ? '<=' : '>='); | |
979 | $operator = ($actionSchedule->start_action_condition == 'before' ? 'DATE_SUB' : 'DATE_ADD'); | |
980 | $date = $operator . "({$dateField}, INTERVAL {$actionSchedule->start_action_offset} {$actionSchedule->start_action_unit})"; | |
6a488035 TO |
981 | $startDateClause[] = "'{$now}' >= {$date}"; |
982 | if ($mapping->entity == 'civicrm_participant') { | |
983 | $startDateClause[] = $operator. "({$now}, INTERVAL 1 DAY ) {$op} " . $dateField; | |
984 | } | |
985 | else { | |
986 | $startDateClause[] = "DATE_SUB({$now}, INTERVAL 1 DAY ) <= {$date}"; | |
987 | } | |
988 | ||
989 | $startDate = implode(' AND ', $startDateClause); | |
990 | } | |
991 | elseif ($actionSchedule->absolute_date) { | |
992 | $startDate = "DATEDIFF(DATE('{$now}'),'{$actionSchedule->absolute_date}') = 0"; | |
993 | } | |
994 | ||
995 | // ( now >= date_built_from_start_time ) OR ( now = absolute_date ) | |
996 | $dateClause = "reminder.id IS NULL AND {$startDate}"; | |
997 | ||
998 | // start composing query | |
999 | $selectClause = 'SELECT ' . implode(', ', $select); | |
3e315abc | 1000 | $fromClause = "FROM $from"; |
1001 | $joinClause = !empty($join) ? implode(' ', $join) : ''; | |
1002 | $whereClause = 'WHERE ' . implode(' AND ', $where); | |
7188a78d PJ |
1003 | $limitWhereClause = ''; |
1004 | if (!empty($limitWhere)) { | |
1005 | $limitWhereClause = ' AND ' . implode(' AND ', $limitWhere); | |
1006 | } | |
6cb6ba4c | 1007 | |
6a488035 TO |
1008 | $query = " |
1009 | INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) | |
1010 | {$selectClause} | |
1011 | {$fromClause} | |
1012 | {$joinClause} | |
1013 | LEFT JOIN {$reminderJoinClause} | |
7188a78d | 1014 | {$whereClause} {$limitWhereClause} AND {$dateClause} {$notINClause} |
bb56ad3d | 1015 | "; |
6a488035 TO |
1016 | CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer'))); |
1017 | ||
bb56ad3d | 1018 | if ($limitTo == 0) { |
82bf20c7 PJ |
1019 | $additionWhere = ' WHERE '; |
1020 | if ($actionSchedule->start_action_date) { | |
60d5bcb0 | 1021 | $additionWhere = $whereClause . ' AND '; |
82bf20c7 | 1022 | } |
3874157e PJ |
1023 | $contactTable = "civicrm_contact c"; |
1024 | $addSelect = "SELECT c.id as contact_id, c.id as entity_id, 'civicrm_contact' as entity_table, {$actionSchedule->id} as action_schedule_id"; | |
1025 | $additionReminderClause = "civicrm_action_log reminder ON reminder.contact_id = c.id AND | |
1026 | reminder.entity_id = c.id AND | |
1027 | reminder.entity_table = 'civicrm_contact' AND | |
1028 | reminder.action_schedule_id = {$actionSchedule->id}"; | |
8010925d | 1029 | $addWhereClause = ''; |
1030 | if ($addWhere) { | |
1031 | $addWhereClause = "AND {$addWhere}"; | |
1032 | } | |
bb56ad3d PJ |
1033 | $insertAdditionalSql =" |
1034 | INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) | |
3874157e PJ |
1035 | {$addSelect} |
1036 | FROM ({$contactTable}, {$table}) | |
1037 | LEFT JOIN {$additionReminderClause} | |
bb56ad3d | 1038 | {$addGroup} |
8010925d | 1039 | {$additionWhere} c.is_deleted = 0 AND c.is_deceased = 0 |
1040 | {$addWhereClause} | |
82bf20c7 PJ |
1041 | AND {$dateClause} |
1042 | AND c.id NOT IN ( | |
bb56ad3d PJ |
1043 | SELECT rem.contact_id |
1044 | FROM civicrm_action_log rem INNER JOIN {$mapping->entity} e ON rem.entity_id = e.id | |
1045 | WHERE rem.action_schedule_id = {$actionSchedule->id} | |
1046 | AND rem.entity_table = '{$mapping->entity}' | |
1047 | ) | |
7188a78d | 1048 | GROUP BY c.id |
bb56ad3d PJ |
1049 | "; |
1050 | CRM_Core_DAO::executeQuery($insertAdditionalSql); | |
1051 | } | |
6a488035 TO |
1052 | // if repeat is turned ON: |
1053 | if ($actionSchedule->is_repeat) { | |
1054 | $repeatEvent = ($actionSchedule->end_action == 'before' ? 'DATE_SUB' : 'DATE_ADD') . "({$dateField}, INTERVAL {$actionSchedule->end_frequency_interval} {$actionSchedule->end_frequency_unit})"; | |
1055 | ||
1056 | if ($actionSchedule->repetition_frequency_unit == 'day') { | |
1057 | $hrs = 24 * $actionSchedule->repetition_frequency_interval; | |
1058 | } | |
1059 | elseif ($actionSchedule->repetition_frequency_unit == 'week') { | |
1060 | $hrs = 24 * $actionSchedule->repetition_frequency_interval * 7; | |
1061 | } | |
1062 | else { | |
1063 | $hrs = $actionSchedule->repetition_frequency_interval; | |
1064 | } | |
1065 | ||
1066 | // (now <= repeat_end_time ) | |
1067 | $repeatEventClause = "'{$now}' <= {$repeatEvent}"; | |
1068 | // diff(now && logged_date_time) >= repeat_interval | |
1069 | $havingClause = "HAVING TIMEDIFF({$now}, latest_log_time) >= TIME('{$hrs}:00:00')"; | |
1070 | $groupByClause = 'GROUP BY reminder.contact_id, reminder.entity_id, reminder.entity_table'; | |
1071 | $selectClause .= ', MAX(reminder.action_date_time) as latest_log_time'; | |
6a488035 TO |
1072 | $sqlInsertValues = "{$selectClause} |
1073 | {$fromClause} | |
1074 | {$joinClause} | |
1075 | INNER JOIN {$reminderJoinClause} | |
3874157e | 1076 | {$whereClause} {$limitWhereClause} AND {$repeatEventClause} |
6a488035 TO |
1077 | {$groupByClause} |
1078 | {$havingClause}"; | |
1079 | ||
1080 | $valsqlInsertValues = CRM_Core_DAO::executeQuery($sqlInsertValues, array(1 => array($actionSchedule->id, 'Integer'))); | |
1081 | ||
1082 | $arrValues = array(); | |
1083 | while ($valsqlInsertValues->fetch()) { | |
1084 | $arrValues[] = "( {$valsqlInsertValues->contact_id}, {$valsqlInsertValues->entity_id}, '{$valsqlInsertValues->entity_table}',{$valsqlInsertValues->action_schedule_id} )"; | |
1085 | } | |
1086 | ||
1087 | $valString = implode(',', $arrValues); | |
1088 | ||
1089 | if ($valString) { | |
1090 | $query = ' | |
1091 | INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString; | |
1092 | CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer'))); | |
1093 | } | |
3874157e PJ |
1094 | |
1095 | if ($limitTo == 0) { | |
1096 | $addSelect .= ', MAX(reminder.action_date_time) as latest_log_time'; | |
1097 | $sqlEndEventCheck = " | |
1098 | SELECT * FROM {$table} | |
1099 | {$whereClause} AND {$repeatEventClause} LIMIT 1"; | |
1100 | ||
1101 | $daoCheck = CRM_Core_DAO::executeQuery($sqlEndEventCheck); | |
1102 | if ($daoCheck->fetch()) { | |
1103 | $valSqlAdditionInsert = " | |
1104 | {$addSelect} | |
1105 | FROM {$contactTable} | |
1106 | {$addGroup} | |
1107 | INNER JOIN {$additionReminderClause} | |
1108 | WHERE {$addWhere} AND c.is_deleted = 0 AND c.is_deceased = 0 | |
1109 | GROUP BY reminder.contact_id | |
1110 | {$havingClause} | |
1111 | "; | |
1112 | $daoForVals = CRM_Core_DAO::executeQuery($valSqlAdditionInsert); | |
1113 | $addValues = array(); | |
1114 | while ($daoForVals->fetch()) { | |
1115 | $addValues[] = "( {$daoForVals->contact_id}, {$daoForVals->entity_id}, '{$daoForVals->entity_table}',{$daoForVals->action_schedule_id} )"; | |
1116 | } | |
1117 | $valString = implode(',', $addValues); | |
1118 | ||
1119 | if ($valString) { | |
1120 | $query = ' | |
1121 | INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString; | |
1122 | CRM_Core_DAO::executeQuery($query); | |
1123 | } | |
1124 | } | |
1125 | } | |
6a488035 TO |
1126 | } |
1127 | } | |
1128 | } | |
1129 | ||
1130 | static function permissionedRelationships($field) { | |
1131 | $query = ' | |
1132 | SELECT 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 | |
1133 | FROM civicrm_membership m | |
1134 | LEFT JOIN civicrm_membership cm ON cm.id = m.owner_membership_id | |
1135 | LEFT JOIN civicrm_membership_type cmt ON cmt.id = m.membership_type_id | |
1136 | LEFT 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 ) | |
1137 | 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 ) ) | |
1138 | WHERE m.owner_membership_id IS NOT NULL AND | |
1139 | ( rel.is_permission_a_b = 0 OR rel.is_permission_b_a = 0) | |
1140 | ||
1141 | '; | |
1142 | $excludeIds = array(); | |
1143 | $dao = CRM_Core_DAO::executeQuery($query, array()); | |
1144 | while ($dao->fetch()) { | |
1145 | if ($dao->slave_contact == $dao->contact_id_a && $dao->is_permission_b_a == 0) { | |
1146 | $excludeIds[] = $dao->slave_contact; | |
1147 | } | |
1148 | elseif ($dao->slave_contact == $dao->contact_id_b && $dao->is_permission_a_b == 0) { | |
1149 | $excludeIds[] = $dao->slave_contact; | |
1150 | } | |
1151 | } | |
1152 | ||
1153 | if (!empty($excludeIds)) { | |
1154 | $clause = "AND {$field} NOT IN ( " .implode(', ', $excludeIds) . ' ) '; | |
1155 | return $clause; | |
1156 | } | |
1157 | return NULL; | |
1158 | } | |
1159 | ||
1160 | static function processQueue($now = NULL) { | |
1161 | $now = $now ? CRM_Utils_Time::setTime($now) : CRM_Utils_Time::getTime(); | |
1162 | ||
1163 | $mappings = self::getMapping(); | |
1164 | foreach ($mappings as $mappingID => $mapping) { | |
1165 | self::buildRecipientContacts($mappingID, $now); | |
1166 | self::sendMailings($mappingID, $now); | |
1167 | } | |
1168 | ||
1169 | $result = array( | |
1170 | 'is_error' => 0, | |
1171 | 'messages' => ts('Sent all scheduled reminders successfully'), | |
1172 | ); | |
1173 | return $result; | |
1174 | } | |
1175 | ||
1176 | static function isConfigured($id, $mappingID) { | |
1177 | $queryString = "SELECT count(id) FROM civicrm_action_schedule | |
1178 | WHERE mapping_id = %1 AND | |
1179 | entity_value = %2"; | |
1180 | ||
3e315abc | 1181 | $params = array( |
1182 | 1 => array($mappingID, 'Integer'), | |
1183 | 2 => array($id, 'Integer'), | |
6a488035 TO |
1184 | ); |
1185 | return CRM_Core_DAO::singleValueQuery($queryString, $params); | |
1186 | } | |
1187 | ||
1188 | static function getRecipientListing($mappingID, $recipientType) { | |
1189 | $options = array(); | |
1190 | if (!$mappingID || !$recipientType) { | |
1191 | return $options; | |
1192 | } | |
1193 | ||
1194 | $mapping = self::getMapping($mappingID); | |
1195 | ||
1196 | switch ($mapping['entity']) { | |
1197 | case 'civicrm_participant': | |
e7e657f0 | 1198 | $eventContacts = CRM_Core_OptionGroup::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name'); |
6a488035 TO |
1199 | if (!CRM_Utils_Array::value($recipientType, $eventContacts)) { |
1200 | return $options; | |
1201 | } | |
40f2fee3 | 1202 | if ($eventContacts[$recipientType] == 'participant_role') { |
6a488035 TO |
1203 | $options = CRM_Event_PseudoConstant::participantRole(); |
1204 | } | |
1205 | break; | |
1206 | } | |
1207 | ||
1208 | return $options; | |
1209 | } | |
1210 | } | |
1211 |