Import from SVN (r45945, r596)
[civicrm-core.git] / CRM / Core / BAO / ActionSchedule.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
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 */
40class 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();
84 $autoRenew = CRM_Core_PseudoConstant::autoRenew();
85 $membershipType = CRM_Member_PseudoConstant::membershipType();
86
87 asort($activityType);
88
89 $sel1 = $sel2 = $sel3 = $sel4 = $sel5 = array();
90 $options = array('manual' => ts('Choose Recipient(s)'),
91 'group' => ts('Select a Group'),
92 );
93
94 $entityMapping = array();
95 $recipientMapping = array_combine(array_keys($options), array_keys($options));
96
97 if (!$id) {
98 $id = 1;
99 }
100
101 foreach ($mapping as $value) {
102 $entityValue = CRM_Utils_Array::value('entity_value', $value);
103 $entityStatus = CRM_Utils_Array::value('entity_status', $value);
104 $entityRecipient = CRM_Utils_Array::value('entity_recipient', $value);
105 $valueLabel = array('- ' . strtolower(CRM_Utils_Array::value('entity_value_label', $value)) . ' -');
106 $key = CRM_Utils_Array::value('id', $value);
107 $entityMapping[$key] = CRM_Utils_Array::value('entity', $value);
108
109 $sel1Val = null;
110 switch ($entityValue) {
111 case 'activity_type':
112 if ($value['entity'] == 'civicrm_activity') {
113 $sel1Val = ts('Activity');
114 }
115 $sel2[$key] = $valueLabel + $activityType;
116 break;
117
118 case 'event_type':
119 if ($value['entity'] == 'civicrm_participant') {
120 $sel1Val = ts('Event Type');
121 }
122 $sel2[$key] = $valueLabel + $eventType;
123 break;
124
125 case 'event_template':
126 if ($value['entity'] == 'civicrm_participant') {
127 $sel1Val = ts('Event Template');
128 }
129 $sel2[$key] = $valueLabel + $eventTemplate;
130 break;
131
132 case 'civicrm_event':
133 if ($value['entity'] == 'civicrm_participant') {
134 $sel1Val = ts('Event Name');
135 }
136 $sel2[$key] = $valueLabel + $event;
137 break;
138
139 case 'civicrm_membership_type':
140 if ($value['entity'] == 'civicrm_membership') {
141 $sel1Val = ts('Membership');
142 }
143 $sel2[$key] = $valueLabel + $membershipType;
144 break;
145 }
146 $sel1[$key] = $sel1Val;
147
148 if ($key == $id) {
149 if ($startDate = CRM_Utils_Array::value('entity_date_start', $value)) {
150 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
151 }
152 if ($endDate = CRM_Utils_Array::value('entity_date_end', $value)) {
153 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
154 }
155
156 switch ($entityRecipient) {
157 case 'activity_contacts':
158 $activityContacts = CRM_Core_PseudoConstant::activityContacts();
159 $sel5[$entityRecipient] = $activityContacts + $options;
160 $recipientMapping += CRM_Core_PseudoConstant::activityContacts('name');
161 break;
162
163 case 'event_contacts':
164 $eventContacts = CRM_Core_PseudoConstant::eventContacts();
165 $sel5[$entityRecipient] = $eventContacts + $options;
166 $recipientMapping += CRM_Core_PseudoConstant::eventContacts('name');
167 break;
168
169 case NULL:
170 $sel5[$entityRecipient] = $options;
171 break;
172 }
173 }
174 }
175 $sel3 = $sel2;
176
177 foreach ($mapping as $value) {
178 $entityStatus = CRM_Utils_Array::value('entity_status', $value);
179 $statusLabel = array('- ' . strtolower(CRM_Utils_Array::value('entity_status_label', $value)) . ' -');
180 $id = CRM_Utils_Array::value('id', $value);
181
182 switch ($entityStatus) {
183 case 'activity_status':
184 foreach ($sel3[$id] as $kkey => & $vval) {
185 $vval = $statusLabel + $activityStatus;
186 }
187 break;
188
189 case 'civicrm_participant_status_type':
190 foreach ($sel3[$id] as $kkey => & $vval) {
191 $vval = $statusLabel + $participantStatus;
192 }
193 break;
194
195 case 'auto_renew_options':
196 foreach ($sel3[$id] as $kkey => & $vval) {
197 $auto = 0;
198 if ($kkey) {
199 $auto = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $kkey, 'auto_renew');
200 }
201 if ( $auto ) {
202 $vval = $statusLabel + $autoRenew;
203 }
204 else {
205 $vval = $statusLabel;
206 }
207 }
208 break;
209
210 case '':
211 $sel3[$id] = '';
212 break;
213
214 }
215 }
216
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);
230 $sel4 = $sel5 = array();
231 $options = array('manual' => ts('Choose Recipient(s)'),
232 'group' => ts('Select a Group'),
233 );
234
235 $recipientMapping = array_combine(array_keys($options), array_keys($options));
236
237 foreach ($mapping as $value) {
238 $entityRecipient = CRM_Utils_Array::value('entity_recipient', $value);
239 $key = CRM_Utils_Array::value('id', $value);
240
241 if ($startDate = CRM_Utils_Array::value('entity_date_start', $value)) {
242 $sel4[$startDate] = ucwords(str_replace('_', ' ', $startDate));
243 }
244 if ($endDate = CRM_Utils_Array::value('entity_date_end', $value)) {
245 $sel4[$endDate] = ucwords(str_replace('_', ' ', $endDate));
246 }
247
248 switch ($entityRecipient) {
249 case 'activity_contacts':
250 $activityContacts = CRM_Core_PseudoConstant::activityContacts();
251 $sel5[$id] = $activityContacts + $options;
252 $recipientMapping += CRM_Core_PseudoConstant::activityContacts('name');
253 break;
254
255 case 'event_contacts':
256 $eventContacts = CRM_Core_PseudoConstant::eventContacts();
257 $sel5[$id] = $eventContacts + $options;
258 $recipientMapping += CRM_Core_PseudoConstant::eventContacts('name');
259 break;
260
261 case NULL:
262 $sel5[$id] = $options;
263 break;
264 }
265 }
266
267 return array(
268 'sel4' => $sel4,
269 'sel5' => $sel5[$id],
270 'recipientMapping' => $recipientMapping,
271 );
272 }
273
274 /**
275 * Retrieve list of Scheduled Reminders
276 *
277 * @param bool $namesOnly return simple list of names
278 *
279 * @return array (reference) reminder list
280 * @static
281 * @access public
282 */
283 static function &getList($namesOnly = FALSE, $entityValue = NULL, $id = NULL) {
284 $activity_type = CRM_Core_PseudoConstant::activityType(FALSE) + CRM_Core_PseudoConstant::activityType(FALSE, TRUE);
285 $activity_status = CRM_Core_PseudoConstant::activityStatus();
286
287 $event_type = CRM_Event_PseudoConstant::eventType();
288 $civicrm_event = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
289 $civicrm_participant_status_type = CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label');
290 $event_template = CRM_Event_PseudoConstant::eventTemplates();
291
292 $auto_renew_options = CRM_Core_PseudoConstant::autoRenew();
293 $civicrm_membership_type = CRM_Member_PseudoConstant::membershipType();
294
295 asort($activity_type);
296 $entity = array(
297 'civicrm_activity' => 'Activity',
298 'civicrm_participant' => 'Event',
299 'civicrm_membership' => 'Member',
300 );
301
302 $query = "
303SELECT
304 title,
305 cam.entity,
306 cas.id as id,
307 cam.entity_value as entityValue,
308 cas.entity_value as entityValueIds,
309 cam.entity_status as entityStatus,
310 cas.entity_status as entityStatusIds,
311 cas.start_action_date as entityDate,
312 cas.start_action_offset,
313 cas.start_action_unit,
314 cas.start_action_condition,
315 cas.absolute_date,
316 is_repeat,
317 is_active
318
319FROM civicrm_action_schedule cas
320LEFT JOIN civicrm_action_mapping cam ON (cam.id = cas.mapping_id)
321";
322 $params = CRM_Core_DAO::$_nullArray;
323
324 if ($entityValue and $id) {
325 $where = "
326WHERE cas.entity_value = $id AND
327 cam.entity_value = '$entityValue'";
328
329 $query .= $where;
330
331 $params = array(1 => array($id, 'Integer'),
332 2 => array($entityValue, 'String'),
333 );
334 }
335
336 $dao = CRM_Core_DAO::executeQuery($query);
337 while ($dao->fetch()) {
338 $list[$dao->id]['id'] = $dao->id;
339 $list[$dao->id]['title'] = $dao->title;
340 $list[$dao->id]['start_action_offset'] = $dao->start_action_offset;
341 $list[$dao->id]['start_action_unit'] = $dao->start_action_unit;
342 $list[$dao->id]['start_action_condition'] = $dao->start_action_condition;
343 $list[$dao->id]['entityDate'] = ucwords(str_replace('_', ' ', $dao->entityDate));
344 $list[$dao->id]['absolute_date'] = $dao->absolute_date;
345
346 $status = $dao->entityStatus;
347 $statusArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $dao->entityStatusIds);
348 foreach ($statusArray as & $s) {
349 $s = CRM_Utils_Array::value($s, $$status);
350 }
351 $statusIds = implode(', ', $statusArray);
352
353 $value = $dao->entityValue;
354 $valueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $dao->entityValueIds);
355 foreach ($valueArray as & $v) {
356 $v = CRM_Utils_Array::value($v, $$value);
357 }
358 $valueIds = implode(', ', $valueArray);
359 $list[$dao->id]['entity'] = $entity[$dao->entity];
360 $list[$dao->id]['value'] = $valueIds;
361 $list[$dao->id]['status'] = $statusIds;
362 $list[$dao->id]['is_repeat'] = $dao->is_repeat;
363 $list[$dao->id]['is_active'] = $dao->is_active;
364 }
365
366 return $list;
367 }
368
369 static function sendReminder($contactId, $email, $scheduleID, $from, $tokenParams) {
370
371 $schedule = new CRM_Core_DAO_ActionSchedule();
372 $schedule->id = $scheduleID;
373
374 $domain = CRM_Core_BAO_Domain::getDomain();
375 $result = NULL;
376 $hookTokens = array();
377
378 if ($schedule->find(TRUE)) {
379 $body_text = $schedule->body_text;
380 $body_html = $schedule->body_html;
381 $body_subject = $schedule->subject;
382 if (!$body_text) {
383 $body_text = CRM_Utils_String::htmlToText($body_html);
384 }
385
386 $params = array(array('contact_id', '=', $contactId, 0, 0));
387 list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($params);
388
389 //CRM-4524
390 $contact = reset($contact);
391
392 if (!$contact || is_a($contact, 'CRM_Core_Error')) {
393 return NULL;
394 }
395
396 // merge activity tokens with contact array
397 $contact = array_merge($contact, $tokenParams);
398
399 //CRM-5734
400 CRM_Utils_Hook::tokenValues($contact, $contactId);
401
402 CRM_Utils_Hook::tokens($hookTokens);
403 $categories = array_keys($hookTokens);
404
405 $type = array('html', 'text');
406
407 foreach ($type as $key => $value) {
408 $dummy_mail = new CRM_Mailing_BAO_Mailing();
409 $bodyType = "body_{$value}";
410 $dummy_mail->$bodyType = $$bodyType;
411 $tokens = $dummy_mail->getTokens();
412
413 if ($$bodyType) {
414 CRM_Utils_Token::replaceGreetingTokens($$bodyType, NULL, $contact['contact_id']);
415 $$bodyType = CRM_Utils_Token::replaceDomainTokens($$bodyType, $domain, TRUE, $tokens[$value], TRUE);
416 $$bodyType = CRM_Utils_Token::replaceContactTokens($$bodyType, $contact, FALSE, $tokens[$value], FALSE, TRUE);
417 $$bodyType = CRM_Utils_Token::replaceComponentTokens($$bodyType, $contact, $tokens[$value], TRUE, FALSE);
418 $$bodyType = CRM_Utils_Token::replaceHookTokens($$bodyType, $contact, $categories, TRUE);
419 }
420 }
421 $html = $body_html;
422 $text = $body_text;
423
424 $smarty = CRM_Core_Smarty::singleton();
425 foreach (array(
426 'text', 'html') as $elem) {
427 $$elem = $smarty->fetch("string:{$$elem}");
428 }
429
430 $matches = array();
431 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
432 $body_subject,
433 $matches,
434 PREG_PATTERN_ORDER
435 );
436
437 $subjectToken = NULL;
438 if ($matches[1]) {
439 foreach ($matches[1] as $token) {
440 list($type, $name) = preg_split('/\./', $token, 2);
441 if ($name) {
442 if (!isset($subjectToken['contact'])) {
443 $subjectToken['contact'] = array();
444 }
445 $subjectToken['contact'][] = $name;
446 }
447 }
448 }
449
450 $messageSubject = CRM_Utils_Token::replaceContactTokens($body_subject, $contact, FALSE, $subjectToken);
451 $messageSubject = CRM_Utils_Token::replaceDomainTokens($messageSubject, $domain, TRUE, $tokens[$value]);
452 $messageSubject = CRM_Utils_Token::replaceComponentTokens($messageSubject, $contact, $tokens[$value], TRUE);
453 $messageSubject = CRM_Utils_Token::replaceHookTokens($messageSubject, $contact, $categories, TRUE);
454
455 $messageSubject = $smarty->fetch("string:{$messageSubject}");
456
457 // set up the parameters for CRM_Utils_Mail::send
458 $mailParams = array(
459 'groupName' => 'Scheduled Reminder Sender',
460 'from' => $from,
461 'toName' => $contact['display_name'],
462 'toEmail' => $email,
463 'subject' => $messageSubject,
464 );
465
466 if (!$html || $contact['preferred_mail_format'] == 'Text' ||
467 $contact['preferred_mail_format'] == 'Both'
468 ) {
469 // render the &amp; entities in text mode, so that the links work
470 $mailParams['text'] = str_replace('&amp;', '&', $text);
471 }
472 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
473 $contact['preferred_mail_format'] == 'Both'
474 )) {
475 $mailParams['html'] = $html;
476 }
477
478 $result = CRM_Utils_Mail::send($mailParams);
479 }
480 $schedule->free();
481
482 return $result;
483 }
484
485 /**
486 * Function to add the schedules reminders in the db
487 *
488 * @param array $params (reference ) an assoc array of name/value pairs
489 * @param array $ids the array that holds all the db ids
490 *
491 * @return object CRM_Core_DAO_ActionSchedule
492 * @access public
493 * @static
494 *
495 */
496 static function add(&$params, &$ids) {
497 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
498 $actionSchedule->copyValues($params);
499
500 return $actionSchedule->save();
501 }
502
503 /**
504 * Takes a bunch of params that are needed to match certain criteria and
505 * retrieves the relevant objects. It also stores all the retrieved
506 * values in the default array
507 *
508 * @param array $params (reference ) an assoc array of name/value pairs
509 * @param array $values (reference ) an assoc array to hold the flattened values
510 *
511 * @return object CRM_Core_DAO_ActionSchedule object on success, null otherwise
512 * @access public
513 * @static
514 */
515 static function retrieve(&$params, &$values) {
516 if (empty($params)) {
517 return NULL;
518 }
519 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
520
521 $actionSchedule->copyValues($params);
522
523 if ($actionSchedule->find(TRUE)) {
524 $ids['actionSchedule'] = $actionSchedule->id;
525
526 CRM_Core_DAO::storeValues($actionSchedule, $values);
527
528 return $actionSchedule;
529 }
530 return NULL;
531 }
532
533 /**
534 * Function to delete a Reminder
535 *
536 * @param int $id ID of the Reminder to be deleted.
537 *
538 * @access public
539 * @static
540 */
541 static function del($id) {
542 if ($id) {
543 $dao = new CRM_Core_DAO_ActionSchedule();
544 $dao->id = $id;
545 if ($dao->find(TRUE)) {
546 $dao->delete();
547 return;
548 }
549 }
550 CRM_Core_Error::fatal(ts('Invalid value passed to delete function.'));
551 }
552
553 /**
554 * update the is_active flag in the db
555 *
556 * @param int $id id of the database record
557 * @param boolean $is_active value we want to set the is_active field
558 *
559 * @return Object DAO object on success, null otherwise
560 * @static
561 */
562 static function setIsActive($id, $is_active) {
563 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
564 }
565
566 static function sendMailings($mappingID, $now) {
567 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
568 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
569
570 $mapping = new CRM_Core_DAO_ActionMapping();
571 $mapping->id = $mappingID;
572 $mapping->find(TRUE);
573
574 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
575 $actionSchedule->mapping_id = $mappingID;
576 $actionSchedule->is_active = 1;
577 $actionSchedule->find(FALSE);
578
579 $tokenFields = array();
580 $session = CRM_Core_Session::singleton();
581
582 while ($actionSchedule->fetch()) {
583 $extraSelect = $extraJoin = $extraWhere = '';
584
585 if ($actionSchedule->record_activity) {
586 if ($mapping->entity == 'civicrm_membership') {
587 $activityTypeID =
588 CRM_Core_OptionGroup::getValue('activity_type', 'Membership Renewal Reminder', 'name');
589 }
590 else {
591 $activityTypeID =
592 CRM_Core_OptionGroup::getValue('activity_type', 'Reminder Sent', 'name');
593 }
594
595 $activityStatusID =
596 CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name');
597 }
598
599 if ($mapping->entity == 'civicrm_activity') {
600 $tokenEntity = 'activity';
601 $tokenFields = array('activity_id', 'activity_type', 'subject', 'details', 'activity_date_time');
602 $extraSelect = ', ov.label as activity_type, e.id as activity_id';
603 $extraJoin = "INNER JOIN civicrm_option_group og ON og.name = 'activity_type'
604INNER JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
605 $extraWhere = 'AND e.is_current_revision = 1 AND e.is_deleted = 0';
606 }
607
608 if ($mapping->entity == 'civicrm_participant') {
609 $tokenEntity = 'event';
610 $tokenFields = array('event_type', 'title', 'event_id', 'start_date', 'end_date', 'summary', 'description', 'location', 'info_url', 'registration_url', 'fee_amount', 'contact_email', 'contact_phone');
611 $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 ';
612
613 $extraJoin = "
614INNER JOIN civicrm_event ev ON e.event_id = ev.id
615INNER JOIN civicrm_option_group og ON og.name = 'event_type'
616INNER JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
617LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
618LEFT JOIN civicrm_address address ON address.id = lb.address_id
619LEFT JOIN civicrm_email email ON email.id = lb.email_id
620LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
621";
622 }
623
624 if ($mapping->entity == 'civicrm_membership') {
625 $tokenEntity = 'membership';
626 $tokenFields = array('fee', 'id', 'join_date', 'start_date', 'end_date', 'status', 'type');
627 $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';
628 $extraJoin = '
629 INNER JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
630 INNER JOIN civicrm_membership_status ms ON e.status_id = ms.id';
631 }
632
633 $query = "
634SELECT reminder.id as reminderID, reminder.*, e.id as entityID, e.* {$extraSelect}
635FROM civicrm_action_log reminder
636INNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id
637{$extraJoin}
638WHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL
639{$extraWhere}";
640
641 $dao = CRM_Core_DAO::executeQuery($query,
642 array(1 => array($actionSchedule->id, 'Integer'))
643 );
644
645 while ($dao->fetch()) {
646 $entityTokenParams = array();
647 foreach ($tokenFields as $field) {
648 if ($field == 'location') {
649 $loc = array();
650 $stateProvince = CRM_Core_PseudoConstant::stateProvince();
651 $loc['street_address'] = $dao->street_address;
652 $loc['city'] = $dao->city;
653 $loc['state_province'] = CRM_Utils_array::value($dao->state_province_id, $stateProvince);
654 $loc['postal_code'] = $dao->postal_code;
655 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address::format($loc);
656 }
657 elseif ($field == 'info_url') {
658 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE);
659 }
660 elseif ($field == 'registration_url') {
661 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE);
662 }
663 elseif (in_array($field, array('start_date','end_date','join_date','activity_date_time'))) {
664 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date::customFormat($dao->$field);
665 }
666 else {
667 $entityTokenParams["{$tokenEntity}." . $field] = $dao->$field;
668 }
669 }
670
671 $isError = 0;
672 $errorMsg = '';
673 $toEmail = CRM_Contact_BAO_Contact::getPrimaryEmail($dao->contact_id);
674 if ($toEmail) {
675 $result =
676 CRM_Core_BAO_ActionSchedule::sendReminder(
677 $dao->contact_id,
678 $toEmail,
679 $actionSchedule->id,
680 $fromEmailAddress,
681 $entityTokenParams
682 );
683
684 if (!$result || is_a($result, 'PEAR_Error')) {
685 // we could not send an email, for now we ignore, CRM-3406
686 $isError = 1;
687 }
688 }
689 else {
690 $isError = 1;
691 $errorMsg = "Couldn\'t find recipient\'s email address.";
692 }
693
694 // update action log record
695 $logParams = array(
696 'id' => $dao->reminderID,
697 'is_error' => $isError,
698 'message' => $errorMsg ? $errorMsg : "null",
699 'action_date_time' => $now,
700 );
701 CRM_Core_BAO_ActionLog::create($logParams);
702
703 // insert activity log record if needed
704 if ($actionSchedule->record_activity) {
705 $activityParams = array(
706 'subject' => $actionSchedule->title,
707 'details' => $actionSchedule->body_html,
708 'source_contact_id' => $session->get('userID') ?
709 $session->get('userID') : $dao->contact_id,
710 'target_contact_id' => $dao->contact_id,
711 'activity_date_time' => date('YmdHis'),
712 'status_id' => $activityStatusID,
713 'activity_type_id' => $activityTypeID,
714 'source_record_id' => $dao->entityID,
715 );
716 $activity = CRM_Activity_BAO_Activity::create($activityParams);
717 }
718 }
719
720 $dao->free();
721 }
722 }
723
724 static function buildRecipientContacts($mappingID, $now) {
725 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
726 $actionSchedule->mapping_id = $mappingID;
727 $actionSchedule->is_active = 1;
728 $actionSchedule->find();
729
730 while ($actionSchedule->fetch()) {
731 $mapping = new CRM_Core_DAO_ActionMapping();
732 $mapping->id = $mappingID;
733 $mapping->find(TRUE);
734
735 $select = $join = $where = array();
736
737 $value = explode(CRM_Core_DAO::VALUE_SEPARATOR,
738 trim($actionSchedule->entity_value, CRM_Core_DAO::VALUE_SEPARATOR)
739 );
740 $value = implode(',', $value);
741
742 $status = explode(CRM_Core_DAO::VALUE_SEPARATOR,
743 trim($actionSchedule->entity_status, CRM_Core_DAO::VALUE_SEPARATOR)
744 );
745 $status = implode(',', $status);
746
747 if (!CRM_Utils_System::isNull($mapping->entity_recipient)) {
748 $recipientOptions = CRM_Core_OptionGroup::values($mapping->entity_recipient);
749 }
750 $from = "{$mapping->entity} e";
751
752 if ($mapping->entity == 'civicrm_activity') {
753 switch ($recipientOptions[$actionSchedule->recipient]) {
754 case 'Activity Assignees':
755 $contactField = 'r.assignee_contact_id';
756 $join[] = 'INNER JOIN civicrm_activity_assignment r ON r.activity_id = e.id';
757 break;
758
759 case 'Activity Source':
760 $contactField = 'e.source_contact_id';
761 break;
762
763 case 'Activity Targets':
764 $contactField = 'r.target_contact_id';
765 $join[] = 'INNER JOIN civicrm_activity_target r ON r.activity_id = e.id';
766 break;
767
768 default:
769 break;
770 }
771 // build where clause
772 if (!empty($value)) {
773 $where[] = "e.activity_type_id IN ({$value})";
774 }
775 else {
776 $where[] = "e.activity_type_id IS NULL";
777 }
778 if (!empty($status)) {
779 $where[] = "e.status_id IN ({$status})";
780 }
781 $where[] = ' e.is_current_revision = 1 ';
782 $where[] = ' e.is_deleted = 0 ';
783
784 $dateField = 'e.activity_date_time';
785 }
786
787 if ($mapping->entity == 'civicrm_participant') {
788 $contactField = 'e.contact_id';
789 $join[] = 'INNER JOIN civicrm_event r ON e.event_id = r.id';
790 if ($actionSchedule->recipient_listing) {
791 $rList = explode(CRM_Core_DAO::VALUE_SEPARATOR,
792 trim($actionSchedule->recipient_listing, CRM_Core_DAO::VALUE_SEPARATOR)
793 );
794 $rList = implode(',', $rList);
795
796 switch ($recipientOptions[$actionSchedule->recipient]) {
797 case 'Participant Role':
798 $where[] = "e.role_id IN ({$rList})";
799 break;
800
801 default:
802 break;
803 }
804 }
805
806 // build where clause
807 if (!empty($value)) {
808 $where[] = ($mapping->entity_value == 'event_type') ? "r.event_type_id IN ({$value})" : "r.id IN ({$value})";
809 }
810 else {
811 $where[] = ($mapping->entity_value == 'event_type') ? "r.event_type_id IS NULL" : "r.id IS NULL";
812 }
813
814 if (!empty($status)) {
815 $where[] = "e.status_id IN ({$status})";
816 }
817
818 $where[] = 'r.is_active = 1';
819 $where[] = 'r.is_template = 0';
820 $dateField = str_replace('event_', 'r.', $actionSchedule->start_action_date);
821 }
822
823 $notINClause = '';
824 if ($mapping->entity == 'civicrm_membership') {
825 $contactField = 'e.contact_id';
826
827 // build where clause
828 if ( $status == 2 ) {
829 //auto-renew memberships
830 $where[] = "e.contribution_recur_id IS NOT NULL ";
831 }
832 elseif ( $status == 1 ) {
833 $where[] = "e.contribution_recur_id IS NULL ";
834 }
835
836 // build where clause
837 if (!empty($value)) {
838 $where[] = "e.membership_type_id IN ({$value})";
839 }
840 else {
841 $where[] = "e.membership_type_id IS NULL";
842 }
843
844 $dateField = str_replace('membership_', 'e.', $actionSchedule->start_action_date);
845 $notINClause = self::permissionedRelationships($contactField);
846 }
847
848 if ($actionSchedule->group_id) {
849 $join[] = "INNER JOIN civicrm_group_contact grp ON {$contactField} = grp.contact_id AND grp.status = 'Added'";
850 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
851 }
852 elseif (!empty($actionSchedule->recipient_manual)) {
853 $rList = CRM_Utils_Type::escape($actionSchedule->recipient_manual, 'String');
854 $where[] = "{$contactField} IN ({$rList})";
855 }
856
857 $select[] = "{$contactField} as contact_id";
858 $select[] = 'e.id as entity_id';
859 $select[] = "'{$mapping->entity}' as entity_table";
860 $select[] = "{$actionSchedule->id} as action_schedule_id";
861 $reminderJoinClause = "civicrm_action_log reminder ON reminder.contact_id = {$contactField} AND
862reminder.entity_id = e.id AND
863reminder.entity_table = '{$mapping->entity}' AND
864reminder.action_schedule_id = %1";
865
866 $join[] = "INNER JOIN civicrm_contact c ON c.id = {$contactField}";
867 $where[] = 'c.is_deleted = 0';
868
869 if ($actionSchedule->start_action_date) {
870 $startDateClause = array();
871 $op = ($actionSchedule->start_action_condition == 'before' ? '<=' : '>=');
872 $operator = ($actionSchedule->start_action_condition == 'before' ? 'DATE_SUB' : 'DATE_ADD');
873 $date = $operator . "({$dateField}, INTERVAL {$actionSchedule->start_action_offset} {$actionSchedule->start_action_unit})";
874 $startDateClause[] = "'{$now}' >= {$date}";
875 if ($mapping->entity == 'civicrm_participant') {
876 $startDateClause[] = $operator. "({$now}, INTERVAL 1 DAY ) {$op} " . $dateField;
877 }
878 else {
879 $startDateClause[] = "DATE_SUB({$now}, INTERVAL 1 DAY ) <= {$date}";
880 }
881
882 $startDate = implode(' AND ', $startDateClause);
883 }
884 elseif ($actionSchedule->absolute_date) {
885 $startDate = "DATEDIFF(DATE('{$now}'),'{$actionSchedule->absolute_date}') = 0";
886 }
887
888 // ( now >= date_built_from_start_time ) OR ( now = absolute_date )
889 $dateClause = "reminder.id IS NULL AND {$startDate}";
890
891 // start composing query
892 $selectClause = 'SELECT ' . implode(', ', $select);
893 $fromClause = "FROM $from";
894 $joinClause = !empty($join) ? implode(' ', $join) : '';
895 $whereClause = 'WHERE ' . implode(' AND ', $where);
896
897 $query = "
898INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
899{$selectClause}
900{$fromClause}
901{$joinClause}
902LEFT JOIN {$reminderJoinClause}
903{$whereClause} AND {$dateClause} {$notINClause}";
904
905 CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer')));
906
907 // if repeat is turned ON:
908 if ($actionSchedule->is_repeat) {
909 $repeatEvent = ($actionSchedule->end_action == 'before' ? 'DATE_SUB' : 'DATE_ADD') . "({$dateField}, INTERVAL {$actionSchedule->end_frequency_interval} {$actionSchedule->end_frequency_unit})";
910
911 if ($actionSchedule->repetition_frequency_unit == 'day') {
912 $hrs = 24 * $actionSchedule->repetition_frequency_interval;
913 }
914 elseif ($actionSchedule->repetition_frequency_unit == 'week') {
915 $hrs = 24 * $actionSchedule->repetition_frequency_interval * 7;
916 }
917 else {
918 $hrs = $actionSchedule->repetition_frequency_interval;
919 }
920
921 // (now <= repeat_end_time )
922 $repeatEventClause = "'{$now}' <= {$repeatEvent}";
923 // diff(now && logged_date_time) >= repeat_interval
924 $havingClause = "HAVING TIMEDIFF({$now}, latest_log_time) >= TIME('{$hrs}:00:00')";
925 $groupByClause = 'GROUP BY reminder.contact_id, reminder.entity_id, reminder.entity_table';
926 $selectClause .= ', MAX(reminder.action_date_time) as latest_log_time';
927
928 $sqlInsertValues = "{$selectClause}
929{$fromClause}
930{$joinClause}
931INNER JOIN {$reminderJoinClause}
932{$whereClause} AND {$repeatEventClause}
933{$groupByClause}
934{$havingClause}";
935
936 $valsqlInsertValues = CRM_Core_DAO::executeQuery($sqlInsertValues, array(1 => array($actionSchedule->id, 'Integer')));
937
938 $arrValues = array();
939 while ($valsqlInsertValues->fetch()) {
940 $arrValues[] = "( {$valsqlInsertValues->contact_id}, {$valsqlInsertValues->entity_id}, '{$valsqlInsertValues->entity_table}',{$valsqlInsertValues->action_schedule_id} )";
941 }
942
943 $valString = implode(',', $arrValues);
944
945 if ($valString) {
946 $query = '
947 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
948 CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer')));
949 }
950 }
951 }
952 }
953
954 static function permissionedRelationships($field) {
955 $query = '
956SELECT 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
957FROM civicrm_membership m
958LEFT JOIN civicrm_membership cm ON cm.id = m.owner_membership_id
959LEFT JOIN civicrm_membership_type cmt ON cmt.id = m.membership_type_id
960LEFT 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 )
961 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 ) )
962WHERE m.owner_membership_id IS NOT NULL AND
963 ( rel.is_permission_a_b = 0 OR rel.is_permission_b_a = 0)
964
965';
966 $excludeIds = array();
967 $dao = CRM_Core_DAO::executeQuery($query, array());
968 while ($dao->fetch()) {
969 if ($dao->slave_contact == $dao->contact_id_a && $dao->is_permission_b_a == 0) {
970 $excludeIds[] = $dao->slave_contact;
971 }
972 elseif ($dao->slave_contact == $dao->contact_id_b && $dao->is_permission_a_b == 0) {
973 $excludeIds[] = $dao->slave_contact;
974 }
975 }
976
977 if (!empty($excludeIds)) {
978 $clause = "AND {$field} NOT IN ( " .implode(', ', $excludeIds) . ' ) ';
979 return $clause;
980 }
981 return NULL;
982 }
983
984 static function processQueue($now = NULL) {
985 $now = $now ? CRM_Utils_Time::setTime($now) : CRM_Utils_Time::getTime();
986
987 $mappings = self::getMapping();
988 foreach ($mappings as $mappingID => $mapping) {
989 self::buildRecipientContacts($mappingID, $now);
990 self::sendMailings($mappingID, $now);
991 }
992
993 $result = array(
994 'is_error' => 0,
995 'messages' => ts('Sent all scheduled reminders successfully'),
996 );
997 return $result;
998 }
999
1000 static function isConfigured($id, $mappingID) {
1001 $queryString = "SELECT count(id) FROM civicrm_action_schedule
1002 WHERE mapping_id = %1 AND
1003 entity_value = %2";
1004
1005 $params = array(1 => array($mappingID, 'Integer'),
1006 2 => array($id, 'Integer'),
1007 );
1008 return CRM_Core_DAO::singleValueQuery($queryString, $params);
1009 }
1010
1011 static function getRecipientListing($mappingID, $recipientType) {
1012 $options = array();
1013 if (!$mappingID || !$recipientType) {
1014 return $options;
1015 }
1016
1017 $mapping = self::getMapping($mappingID);
1018
1019 switch ($mapping['entity']) {
1020 case 'civicrm_participant':
1021 $eventContacts = CRM_Core_PseudoConstant::eventContacts('name');
1022 if (!CRM_Utils_Array::value($recipientType, $eventContacts)) {
1023 return $options;
1024 }
1025 if ($eventContacts[$recipientType] == 'Participant Role') {
1026 $options = CRM_Event_PseudoConstant::participantRole();
1027 }
1028 break;
1029 }
1030
1031 return $options;
1032 }
1033}
1034