Merge pull request #2507 from lcdservices/CRM-14204
[civicrm-core.git] / CRM / Core / BAO / ActionSchedule.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
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(TRUE, 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_OptionGroup::values('auto_renew_options');
85 $membershipType = CRM_Member_PseudoConstant::membershipType();
86
87 asort($activityType);
88
89 $sel1 = $sel2 = $sel3 = $sel4 = $sel5 = array();
90 $options = array(
91 'manual' => ts('Choose Recipient(s)'),
92 'group' => ts('Select a Group'),
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) {
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);
108 $entityMapping[$key] = CRM_Utils_Array::value('entity', $value);
109
110 $sel1Val = NULL;
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':
159 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts');
160 $sel5[$entityRecipient] = $activityContacts + $options;
161 $recipientMapping += CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
162 break;
163
164 case 'event_contacts':
165 $eventContacts = CRM_Core_OptionGroup::values('event_contacts');
166 $sel5[$entityRecipient] = $eventContacts + $options;
167 $recipientMapping += CRM_Core_OptionGroup::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name');
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);
180 $statusLabel = array('- ' . strtolower(CRM_Utils_Array::value('entity_status_label', $value)) . ' -');
181 $id = CRM_Utils_Array::value('id', $value);
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 }
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(
232 'manual' => ts('Choose Recipient(s)'),
233 'group' => ts('Select a Group'),
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':
251 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts');
252 $sel5[$id] = $activityContacts + $options;
253 $recipientMapping += CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
254 break;
255
256 case 'event_contacts':
257 $eventContacts = CRM_Core_OptionGroup::values('event_contacts');
258 $sel5[$id] = $eventContacts + $options;
259 $recipientMapping += CRM_Core_OptionGroup::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name');
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
293 $auto_renew_options = CRM_Core_OptionGroup::values('auto_renew_options');
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
332 $params = array(
333 1 => array($id, 'Integer'),
334 2 => array($entityValue, 'String'),
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, $to, $scheduleID, $from, $tokenParams) {
372 $email = $to['email'];
373 $phoneNumber = $to['phone'];
374 $schedule = new CRM_Core_DAO_ActionSchedule();
375 $schedule->id = $scheduleID;
376
377 $domain = CRM_Core_BAO_Domain::getDomain();
378 $result = NULL;
379 $hookTokens = array();
380
381 if ($schedule->find(TRUE)) {
382 $body_text = $schedule->body_text;
383 $body_html = $schedule->body_html;
384 $body_subject = $schedule->subject;
385 if (!$body_text) {
386 $body_text = CRM_Utils_String::htmlToText($body_html);
387 }
388
389 $params = array(array('contact_id', '=', $contactId, 0, 0));
390 list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($params);
391
392 //CRM-4524
393 $contact = reset($contact);
394
395 if (!$contact || is_a($contact, 'CRM_Core_Error')) {
396 return NULL;
397 }
398
399 // merge activity tokens with contact array
400 $contact = array_merge($contact, $tokenParams);
401
402 //CRM-5734
403 CRM_Utils_Hook::tokenValues($contact, $contactId);
404
405 CRM_Utils_Hook::tokens($hookTokens);
406 $categories = array_keys($hookTokens);
407
408 $type = array('html', 'text');
409
410 foreach ($type as $key => $value) {
411 $dummy_mail = new CRM_Mailing_BAO_Mailing();
412 $bodyType = "body_{$value}";
413 $dummy_mail->$bodyType = $$bodyType;
414 $tokens = $dummy_mail->getTokens();
415
416 if ($$bodyType) {
417 CRM_Utils_Token::replaceGreetingTokens($$bodyType, NULL, $contact['contact_id']);
418 $$bodyType = CRM_Utils_Token::replaceDomainTokens($$bodyType, $domain, TRUE, $tokens[$value], TRUE);
419 $$bodyType = CRM_Utils_Token::replaceContactTokens($$bodyType, $contact, FALSE, $tokens[$value], FALSE, TRUE);
420 $$bodyType = CRM_Utils_Token::replaceComponentTokens($$bodyType, $contact, $tokens[$value], TRUE, FALSE);
421 $$bodyType = CRM_Utils_Token::replaceHookTokens($$bodyType, $contact, $categories, TRUE);
422 }
423 }
424 $html = $body_html;
425 $text = $body_text;
426
427 $smarty = CRM_Core_Smarty::singleton();
428 foreach (array(
429 'text', 'html') as $elem) {
430 $$elem = $smarty->fetch("string:{$$elem}");
431 }
432
433 $matches = array();
434 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
435 $body_subject,
436 $matches,
437 PREG_PATTERN_ORDER
438 );
439
440 $subjectToken = NULL;
441 if ($matches[1]) {
442 foreach ($matches[1] as $token) {
443 list($type, $name) = preg_split('/\./', $token, 2);
444 if ($name) {
445 if (!isset($subjectToken[$type])) {
446 $subjectToken[$type] = array();
447 }
448 $subjectToken[$type][] = $name;
449 }
450 }
451 }
452
453 $messageSubject = CRM_Utils_Token::replaceContactTokens($body_subject, $contact, FALSE, $subjectToken);
454 $messageSubject = CRM_Utils_Token::replaceDomainTokens($messageSubject, $domain, TRUE, $subjectToken);
455 $messageSubject = CRM_Utils_Token::replaceComponentTokens($messageSubject, $contact, $subjectToken, TRUE);
456 $messageSubject = CRM_Utils_Token::replaceHookTokens($messageSubject, $contact, $categories, TRUE);
457
458 $messageSubject = $smarty->fetch("string:{$messageSubject}");
459
460 if ($schedule->mode == 'SMS' or $schedule->mode == 'User_Preference') {
461 $session = CRM_Core_Session::singleton();
462 $userID = $session->get('userID') ? $session->get('userID') : $contactId;
463 $smsParams = array('To' => $phoneNumber, 'provider_id' => $schedule->sms_provider_id, 'activity_subject' => $messageSubject);
464 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
465 'SMS',
466 'name'
467 );
468 $details = $html ? $html : $text;
469 $activityParams = array(
470 'source_contact_id' => $userID,
471 'activity_type_id' => $activityTypeID,
472 'activity_date_time' => date('YmdHis'),
473 'subject' => $messageSubject,
474 'details' => $details,
475 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'),
476 );
477
478 $activity = CRM_Activity_BAO_Activity::create($activityParams);
479
480 CRM_Activity_BAO_Activity::sendSMSMessage($contactId,
481 $text,
482 $html,
483 $smsParams,
484 $activity->id,
485 $userID
486 );
487 }
488
489 if ($schedule->mode == 'Email' or $schedule->mode == 'User_Preference') {
490 // set up the parameters for CRM_Utils_Mail::send
491 $mailParams = array(
492 'groupName' => 'Scheduled Reminder Sender',
493 'from' => $from,
494 'toName' => $contact['display_name'],
495 'toEmail' => $email,
496 'subject' => $messageSubject,
497 'entity' => 'action_schedule',
498 'entity_id' => $scheduleID,
499 );
500
501 if (!$html || $contact['preferred_mail_format'] == 'Text' ||
502 $contact['preferred_mail_format'] == 'Both'
503 ) {
504 // render the &amp; entities in text mode, so that the links work
505 $mailParams['text'] = str_replace('&amp;', '&', $text);
506 }
507 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
508 $contact['preferred_mail_format'] == 'Both'
509 )
510 ) {
511 $mailParams['html'] = $html;
512 }
513 $result = CRM_Utils_Mail::send($mailParams);
514 }
515 }
516 $schedule->free();
517
518 return $result;
519 }
520
521 /**
522 * Function to add the schedules reminders in the db
523 *
524 * @param array $params (reference ) an assoc array of name/value pairs
525 * @param array $ids the array that holds all the db ids
526 *
527 * @return object CRM_Core_DAO_ActionSchedule
528 * @access public
529 * @static
530 *
531 */
532 static function add(&$params, $ids = array()) {
533 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
534 $actionSchedule->copyValues($params);
535
536 return $actionSchedule->save();
537 }
538
539 /**
540 * Takes a bunch of params that are needed to match certain criteria and
541 * retrieves the relevant objects. It also stores all the retrieved
542 * values in the default array
543 *
544 * @param array $params (reference ) an assoc array of name/value pairs
545 * @param array $values (reference ) an assoc array to hold the flattened values
546 *
547 * @return object CRM_Core_DAO_ActionSchedule object on success, null otherwise
548 * @access public
549 * @static
550 */
551 static function retrieve(&$params, &$values) {
552 if (empty($params)) {
553 return NULL;
554 }
555 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
556
557 $actionSchedule->copyValues($params);
558
559 if ($actionSchedule->find(TRUE)) {
560 $ids['actionSchedule'] = $actionSchedule->id;
561
562 CRM_Core_DAO::storeValues($actionSchedule, $values);
563
564 return $actionSchedule;
565 }
566 return NULL;
567 }
568
569 /**
570 * Function to delete a Reminder
571 *
572 * @param int $id ID of the Reminder to be deleted.
573 *
574 * @access public
575 * @static
576 */
577 static function del($id) {
578 if ($id) {
579 $dao = new CRM_Core_DAO_ActionSchedule();
580 $dao->id = $id;
581 if ($dao->find(TRUE)) {
582 $dao->delete();
583 return;
584 }
585 }
586 CRM_Core_Error::fatal(ts('Invalid value passed to delete function.'));
587 }
588
589 /**
590 * update the is_active flag in the db
591 *
592 * @param int $id id of the database record
593 * @param boolean $is_active value we want to set the is_active field
594 *
595 * @return Object DAO object on success, null otherwise
596 * @static
597 */
598 static function setIsActive($id, $is_active) {
599 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_ActionSchedule', $id, 'is_active', $is_active);
600 }
601
602 static function sendMailings($mappingID, $now) {
603 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
604 $fromEmailAddress = "$domainValues[0] <$domainValues[1]>";
605
606 $mapping = new CRM_Core_DAO_ActionMapping();
607 $mapping->id = $mappingID;
608 $mapping->find(TRUE);
609
610 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
611 $actionSchedule->mapping_id = $mappingID;
612 $actionSchedule->is_active = 1;
613 $actionSchedule->find(FALSE);
614
615 $tokenFields = array();
616 $session = CRM_Core_Session::singleton();
617
618 while ($actionSchedule->fetch()) {
619 $extraSelect = $extraJoin = $extraWhere = $extraOn = '';
620
621 if ($actionSchedule->record_activity) {
622 if ($mapping->entity == 'civicrm_membership') {
623 $activityTypeID =
624 CRM_Core_OptionGroup::getValue('activity_type', 'Membership Renewal Reminder', 'name');
625 }
626 else {
627 $activityTypeID =
628 CRM_Core_OptionGroup::getValue('activity_type', 'Reminder Sent', 'name');
629 }
630
631 $activityStatusID =
632 CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name');
633 }
634
635 if ($mapping->entity == 'civicrm_activity') {
636 $tokenEntity = 'activity';
637 $tokenFields = array('activity_id', 'activity_type', 'subject', 'details', 'activity_date_time');
638 $extraSelect = ', ov.label as activity_type, e.id as activity_id';
639 $extraJoin = "
640 INNER JOIN civicrm_option_group og ON og.name = 'activity_type'
641 INNER JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
642 $extraOn = ' AND e.is_current_revision = 1 AND e.is_deleted = 0 ';
643 if ($actionSchedule->limit_to == 0) {
644 $extraJoin = "
645 LEFT JOIN civicrm_option_group og ON og.name = 'activity_type'
646 LEFT JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
647 }
648 }
649
650 if ($mapping->entity == 'civicrm_participant') {
651 $tokenEntity = 'event';
652 $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');
653 $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 ';
654
655 $extraJoin = "
656 INNER JOIN civicrm_event ev ON e.event_id = ev.id
657 INNER JOIN civicrm_option_group og ON og.name = 'event_type'
658 INNER JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
659 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
660 LEFT JOIN civicrm_address address ON address.id = lb.address_id
661 LEFT JOIN civicrm_email email ON email.id = lb.email_id
662 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
663 ";
664 if ($actionSchedule->limit_to == 0) {
665 $extraJoin = "
666 LEFT JOIN civicrm_event ev ON e.event_id = ev.id
667 LEFT JOIN civicrm_option_group og ON og.name = 'event_type'
668 LEFT JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id
669 LEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id
670 LEFT JOIN civicrm_address address ON address.id = lb.address_id
671 LEFT JOIN civicrm_email email ON email.id = lb.email_id
672 LEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id
673 ";
674 }
675 }
676
677 if ($mapping->entity == 'civicrm_membership') {
678 $tokenEntity = 'membership';
679 $tokenFields = array('fee', 'id', 'join_date', 'start_date', 'end_date', 'status', 'type');
680 $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';
681 $extraJoin = '
682 INNER JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
683 INNER JOIN civicrm_membership_status ms ON e.status_id = ms.id';
684
685 if ($actionSchedule->limit_to == 0) {
686 $extraJoin = '
687 LEFT JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
688 LEFT JOIN civicrm_membership_status ms ON e.status_id = ms.id';
689 }
690 }
691
692 $entityJoinClause = "INNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
693 if ($actionSchedule->limit_to == 0) {
694 $entityJoinClause = "LEFT JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
695 $extraWhere .= " AND (e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact')";
696 }
697 $entityJoinClause .= $extraOn;
698
699 $query = "
700 SELECT reminder.id as reminderID, reminder.contact_id as contactID, reminder.*, e.id as entityID, e.* {$extraSelect}
701 FROM civicrm_action_log reminder
702 {$entityJoinClause}
703 {$extraJoin}
704 WHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL
705 {$extraWhere}";
706
707 $dao = CRM_Core_DAO::executeQuery($query,
708 array(1 => array($actionSchedule->id, 'Integer'))
709 );
710
711 while ($dao->fetch()) {
712 $entityTokenParams = array();
713 foreach ($tokenFields as $field) {
714 if ($field == 'location') {
715 $loc = array();
716 $stateProvince = CRM_Core_PseudoConstant::stateProvince();
717 $loc['street_address'] = $dao->street_address;
718 $loc['city'] = $dao->city;
719 $loc['state_province'] = CRM_Utils_Array::value($dao->state_province_id, $stateProvince);
720 $loc['postal_code'] = $dao->postal_code;
721 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address::format($loc);
722 }
723 elseif ($field == 'info_url') {
724 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE);
725 }
726 elseif ($field == 'registration_url') {
727 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE);
728 }
729 elseif (in_array($field, array('start_date','end_date','join_date','activity_date_time'))) {
730 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date::customFormat($dao->$field);
731 }
732 elseif ($field == 'balance') {
733 $info = CRM_Contribute_BAO_Contribution::getPaymentInfo($dao->entityID, 'event');
734 $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Array::value('balance', $info);
735 }
736 else {
737 $entityTokenParams["{$tokenEntity}." . $field] = $dao->$field;
738 }
739 }
740
741 $isError = 0;
742 $errorMsg = $toEmail = $toPhoneNumber = '';
743
744 if ($actionSchedule->mode == 'SMS' or $actionSchedule->mode == 'User_Preference') {
745 $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
746 $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($dao->contactID, FALSE, 'Mobile', $filters);
747 //to get primary mobile ph,if not get a first mobile phONE
748 if (!empty($toPhoneNumbers)) {
749 $toPhoneNumberDetails = reset($toPhoneNumbers);
750 $toPhoneNumber = CRM_Utils_Array::value('phone', $toPhoneNumberDetails);
751 //contact allows to send sms
752 $toDoNotSms = 0;
753 }
754 }
755 if ($actionSchedule->mode == 'Email' or $actionSchedule->mode == 'User_Preference') {
756 $toEmail = CRM_Contact_BAO_Contact::getPrimaryEmail($dao->contactID);
757 }
758 if ($toEmail || !(empty($toPhoneNumber) or $toDoNotSms)) {
759 $to['email'] = $toEmail;
760 $to['phone'] = $toPhoneNumber;
761 $result =
762 CRM_Core_BAO_ActionSchedule::sendReminder(
763 $dao->contactID,
764 $to,
765 $actionSchedule->id,
766 $fromEmailAddress,
767 $entityTokenParams
768 );
769
770 if (!$result || is_a($result, 'PEAR_Error')) {
771 // we could not send an email, for now we ignore, CRM-3406
772 $isError = 1;
773 }
774 }
775 else {
776 $isError = 1;
777 $errorMsg = "Couldn\'t find recipient\'s email address.";
778 }
779
780 // update action log record
781 $logParams = array(
782 'id' => $dao->reminderID,
783 'is_error' => $isError,
784 'message' => $errorMsg ? $errorMsg : "null",
785 'action_date_time' => $now,
786 );
787 CRM_Core_BAO_ActionLog::create($logParams);
788
789 // insert activity log record if needed
790 if ($actionSchedule->record_activity) {
791 $activityParams = array(
792 'subject' => $actionSchedule->title,
793 'details' => $actionSchedule->body_html,
794 'source_contact_id' =>
795 $session->get('userID') ? $session->get('userID') : $dao->contactID,
796 'target_contact_id' => $dao->contactID,
797 'activity_date_time' => date('YmdHis'),
798 'status_id' => $activityStatusID,
799 'activity_type_id' => $activityTypeID,
800 'source_record_id' => $dao->entityID,
801 );
802 $activity = CRM_Activity_BAO_Activity::create($activityParams);
803 }
804 }
805
806 $dao->free();
807 }
808 }
809
810 static function buildRecipientContacts($mappingID, $now, $params = array()) {
811 $actionSchedule = new CRM_Core_DAO_ActionSchedule();
812 $actionSchedule->mapping_id = $mappingID;
813 $actionSchedule->is_active = 1;
814 if(!empty($params)) {
815 _civicrm_api3_dao_set_filter($actionSchedule, $params, FALSE, 'ActionSchedule');
816 }
817 $actionSchedule->find();
818
819 while ($actionSchedule->fetch()) {
820 $mapping = new CRM_Core_DAO_ActionMapping();
821 $mapping->id = $mappingID;
822 $mapping->find(TRUE);
823
824 // note: $where - this filtering applies for both
825 // 'limit to' and 'addition to' options
826 // $limitWhere - this filtering applies only for
827 // 'limit to' option
828 $select = $join = $where = $limitWhere = array();
829 $limitTo = $actionSchedule->limit_to;
830 $value = explode(CRM_Core_DAO::VALUE_SEPARATOR,
831 trim($actionSchedule->entity_value, CRM_Core_DAO::VALUE_SEPARATOR)
832 );
833 $value = implode(',', $value);
834
835 $status = explode(CRM_Core_DAO::VALUE_SEPARATOR,
836 trim($actionSchedule->entity_status, CRM_Core_DAO::VALUE_SEPARATOR)
837 );
838 $status = implode(',', $status);
839
840 if (!CRM_Utils_System::isNull($mapping->entity_recipient)) {
841 $recipientOptions = CRM_Core_OptionGroup::values($mapping->entity_recipient, FALSE, FALSE, FALSE, NULL, 'name');
842 }
843 $from = "{$mapping->entity} e";
844
845 if ($mapping->entity == 'civicrm_activity') {
846 $contactField = 'r.contact_id';
847 $table = 'civicrm_activity e';
848 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
849 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
850 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
851 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
852
853 if ($limitTo == 0) {
854 // including the activity target contacts if 'in addition' is defined
855 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
856 }
857 else {
858 switch (CRM_Utils_Array::value($actionSchedule->recipient, $recipientOptions)) {
859 case 'Activity Assignees':
860 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$assigneeID}";
861 break;
862
863 case 'Activity Source':
864 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$sourceID}";
865 break;
866
867 default:
868 case 'Activity Targets':
869 $join[] = "INNER JOIN civicrm_activity_contact r ON r.activity_id = e.id AND record_type_id = {$targetID}";
870 break;
871 }
872 }
873 // build where clause
874 if (!empty($value)) {
875 $where[] = "e.activity_type_id IN ({$value})";
876 }
877 else {
878 $where[] = "e.activity_type_id IS NULL";
879 }
880 if (!empty($status)) {
881 $where[] = "e.status_id IN ({$status})";
882 }
883 $where[] = ' e.is_current_revision = 1 ';
884 $where[] = ' e.is_deleted = 0 ';
885
886 $dateField = 'e.activity_date_time';
887 }
888
889 if ($mapping->entity == 'civicrm_participant') {
890 $table = 'civicrm_event r';
891 $contactField = 'e.contact_id';
892 $join[] = 'INNER JOIN civicrm_event r ON e.event_id = r.id';
893 if ($actionSchedule->recipient_listing && $limitTo) {
894 $rList = explode(CRM_Core_DAO::VALUE_SEPARATOR,
895 trim($actionSchedule->recipient_listing, CRM_Core_DAO::VALUE_SEPARATOR)
896 );
897 $rList = implode(',', $rList);
898
899 switch ($recipientOptions[$actionSchedule->recipient]) {
900 case 'participant_role':
901 $where[] = "e.role_id IN ({$rList})";
902 break;
903
904 default:
905 break;
906 }
907 }
908
909 // build where clause
910 if (!empty($value)) {
911 $where[] = ($mapping->entity_value == 'event_type') ? "r.event_type_id IN ({$value})" : "r.id IN ({$value})";
912 }
913 else {
914 $where[] = ($mapping->entity_value == 'event_type') ? "r.event_type_id IS NULL" : "r.id IS NULL";
915 }
916
917 // participant status criteria not to be implemented
918 // for additional recipients
919 if (!empty($status)) {
920 $limitWhere[] = "e.status_id IN ({$status})";
921 }
922
923 $where[] = 'r.is_active = 1';
924 $where[] = 'r.is_template = 0';
925 $dateField = str_replace('event_', 'r.', $actionSchedule->start_action_date);
926 }
927
928 $notINClause = '';
929 if ($mapping->entity == 'civicrm_membership') {
930 $contactField = 'e.contact_id';
931 $table = 'civicrm_membership e';
932 // build where clause
933 if ( $status == 2 ) {
934 //auto-renew memberships
935 $where[] = "e.contribution_recur_id IS NOT NULL ";
936 }
937 elseif ( $status == 1 ) {
938 $where[] = "e.contribution_recur_id IS NULL ";
939 }
940
941 // build where clause
942 if (!empty($value)) {
943 $where[] = "e.membership_type_id IN ({$value})";
944 }
945 else {
946 $where[] = "e.membership_type_id IS NULL";
947 }
948
949 $where[] = "( e.is_override IS NULL OR e.is_override = 0 )";
950 $dateField = str_replace('membership_', 'e.', $actionSchedule->start_action_date);
951 $notINClause = self::permissionedRelationships($contactField);
952
953 $membershipStatus = CRM_Member_PseudoConstant::membershipStatus(NULL, "(is_current_member = 1 OR name = 'Expired')", 'id');
954 $mStatus = implode (',', $membershipStatus);
955 $where[] = "e.status_id IN ({$mStatus})";
956 }
957
958 // CRM-13577 Introduce Smart Groups Handling
959 if ($actionSchedule->group_id) {
960
961 // Need to check if its a smart group or not
962 // Then decide which table to join onto the query
963 $group = CRM_Contact_DAO_Group::getTableName();
964
965 // Get the group information
966 $sql = "
967 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
968 FROM $group
969 WHERE $group.id = {$actionSchedule->group_id}
970 ";
971
972 $groupDAO = CRM_Core_DAO::executeQuery($sql);
973 $isSmartGroup = FALSE;
974 if (
975 $groupDAO->fetch() &&
976 !empty($groupDAO->saved_search_id)
977 ) {
978 // Check that the group is in place in the cache and up to date
979 CRM_Contact_BAO_GroupContactCache::check($actionSchedule->group_id);
980 // Set smart group flag
981 $isSmartGroup = TRUE;
982 }
983 }
984 // CRM-13577 End Introduce Smart Groups Handling
985
986 if ($limitTo) {
987 if ($actionSchedule->group_id) {
988 // CRM-13577 If smart group then use Cache table
989 if ($isSmartGroup) {
990 $join[] = "INNER JOIN civicrm_group_contact_cache grp ON {$contactField} = grp.contact_id";
991 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
992 } else {
993 $join[] = "INNER JOIN civicrm_group_contact grp ON {$contactField} = grp.contact_id AND grp.status = 'Added'";
994 $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
995 }
996 }
997 elseif (!empty($actionSchedule->recipient_manual)) {
998 $rList = CRM_Utils_Type::escape($actionSchedule->recipient_manual, 'String');
999 $where[] = "{$contactField} IN ({$rList})";
1000 }
1001 }
1002 else {
1003 $addGroup = $addWhere = '';
1004 if ($actionSchedule->group_id) {
1005 // CRM-13577 If smart group then use Cache table
1006 if ($isSmartGroup) {
1007 $addGroup = " INNER JOIN civicrm_group_contact_cache grp ON c.id = grp.contact_id";
1008 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1009 } else {
1010 $addGroup = " INNER JOIN civicrm_group_contact grp ON c.id = grp.contact_id AND grp.status = 'Added'";
1011 $addWhere = " grp.group_id IN ({$actionSchedule->group_id})";
1012 }
1013 }
1014 if (!empty($actionSchedule->recipient_manual)) {
1015 $rList = CRM_Utils_Type::escape($actionSchedule->recipient_manual, 'String');
1016 $addWhere = "c.id IN ({$rList})";
1017 }
1018 }
1019
1020 $select[] = "{$contactField} as contact_id";
1021 $select[] = 'e.id as entity_id';
1022 $select[] = "'{$mapping->entity}' as entity_table";
1023 $select[] = "{$actionSchedule->id} as action_schedule_id";
1024 $reminderJoinClause = "civicrm_action_log reminder ON reminder.contact_id = {$contactField} AND
1025 reminder.entity_id = e.id AND
1026 reminder.entity_table = '{$mapping->entity}' AND
1027 reminder.action_schedule_id = %1";
1028
1029 $join[] = "INNER JOIN civicrm_contact c ON c.id = {$contactField} AND c.is_deleted = 0 AND c.is_deceased = 0 ";
1030
1031 if ($actionSchedule->start_action_date) {
1032 $startDateClause = array();
1033 $op = ($actionSchedule->start_action_condition == 'before' ? '<=' : '>=');
1034 $operator = ($actionSchedule->start_action_condition == 'before' ? 'DATE_SUB' : 'DATE_ADD');
1035 $date = $operator . "({$dateField}, INTERVAL {$actionSchedule->start_action_offset} {$actionSchedule->start_action_unit})";
1036 $startDateClause[] = "'{$now}' >= {$date}";
1037 if ($mapping->entity == 'civicrm_participant') {
1038 $startDateClause[] = $operator. "({$now}, INTERVAL 1 DAY ) {$op} " . $dateField;
1039 }
1040 else {
1041 $startDateClause[] = "DATE_SUB({$now}, INTERVAL 1 DAY ) <= {$date}";
1042 }
1043
1044 $startDate = implode(' AND ', $startDateClause);
1045 }
1046 elseif ($actionSchedule->absolute_date) {
1047 $startDate = "DATEDIFF(DATE('{$now}'),'{$actionSchedule->absolute_date}') = 0";
1048 }
1049
1050 // ( now >= date_built_from_start_time ) OR ( now = absolute_date )
1051 $dateClause = "reminder.id IS NULL AND {$startDate}";
1052
1053 // start composing query
1054 $selectClause = 'SELECT ' . implode(', ', $select);
1055 $fromClause = "FROM $from";
1056 $joinClause = !empty($join) ? implode(' ', $join) : '';
1057 $whereClause = 'WHERE ' . implode(' AND ', $where);
1058 $limitWhereClause = '';
1059 if (!empty($limitWhere)) {
1060 $limitWhereClause = ' AND ' . implode(' AND ', $limitWhere);
1061 }
1062
1063 $query = "
1064 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1065 {$selectClause}
1066 {$fromClause}
1067 {$joinClause}
1068 LEFT JOIN {$reminderJoinClause}
1069 {$whereClause} {$limitWhereClause} AND {$dateClause} {$notINClause}
1070 ";
1071 CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer')));
1072
1073 if ($limitTo == 0) {
1074 $additionWhere = ' WHERE ';
1075 if ($actionSchedule->start_action_date) {
1076 $additionWhere = $whereClause . ' AND ';
1077 }
1078 $contactTable = "civicrm_contact c";
1079 $addSelect = "SELECT c.id as contact_id, c.id as entity_id, 'civicrm_contact' as entity_table, {$actionSchedule->id} as action_schedule_id";
1080 $additionReminderClause = "civicrm_action_log reminder ON reminder.contact_id = c.id AND
1081 reminder.entity_id = c.id AND
1082 reminder.entity_table = 'civicrm_contact' AND
1083 reminder.action_schedule_id = {$actionSchedule->id}";
1084 $addWhereClause = '';
1085 if ($addWhere) {
1086 $addWhereClause = "AND {$addWhere}";
1087 }
1088 $insertAdditionalSql ="
1089 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)
1090 {$addSelect}
1091 FROM ({$contactTable}, {$table})
1092 LEFT JOIN {$additionReminderClause}
1093 {$addGroup}
1094 {$additionWhere} c.is_deleted = 0 AND c.is_deceased = 0
1095 {$addWhereClause}
1096 AND {$dateClause}
1097 AND c.id NOT IN (
1098 SELECT rem.contact_id
1099 FROM civicrm_action_log rem INNER JOIN {$mapping->entity} e ON rem.entity_id = e.id
1100 WHERE rem.action_schedule_id = {$actionSchedule->id}
1101 AND rem.entity_table = '{$mapping->entity}'
1102 )
1103 GROUP BY c.id
1104 ";
1105 CRM_Core_DAO::executeQuery($insertAdditionalSql);
1106 }
1107 // if repeat is turned ON:
1108 if ($actionSchedule->is_repeat) {
1109 $repeatEvent = ($actionSchedule->end_action == 'before' ? 'DATE_SUB' : 'DATE_ADD') . "({$dateField}, INTERVAL {$actionSchedule->end_frequency_interval} {$actionSchedule->end_frequency_unit})";
1110
1111 if ($actionSchedule->repetition_frequency_unit == 'day') {
1112 $hrs = 24 * $actionSchedule->repetition_frequency_interval;
1113 }
1114 elseif ($actionSchedule->repetition_frequency_unit == 'week') {
1115 $hrs = 24 * $actionSchedule->repetition_frequency_interval * 7;
1116 }
1117 elseif ($actionSchedule->repetition_frequency_unit == 'month') {
1118 $hrs = "24*(DATEDIFF(DATE_ADD(latest_log_time, INTERVAL 1 MONTH ), latest_log_time))";
1119 }
1120 elseif ($actionSchedule->repetition_frequency_unit == 'year') {
1121 $hrs = "24*(DATEDIFF(DATE_ADD(latest_log_time, INTERVAL 1 YEAR ), latest_log_time))";
1122 }
1123 else {
1124 $hrs = $actionSchedule->repetition_frequency_interval;
1125 }
1126
1127 // (now <= repeat_end_time )
1128 $repeatEventClause = "'{$now}' <= {$repeatEvent}";
1129 // diff(now && logged_date_time) >= repeat_interval
1130 $havingClause = "HAVING TIMEDIFF({$now}, latest_log_time) >= TIME('{$hrs}:00:00')";
1131 $groupByClause = 'GROUP BY reminder.contact_id, reminder.entity_id, reminder.entity_table';
1132 $selectClause .= ', MAX(reminder.action_date_time) as latest_log_time';
1133 $sqlInsertValues = "{$selectClause}
1134 {$fromClause}
1135 {$joinClause}
1136 INNER JOIN {$reminderJoinClause}
1137 {$whereClause} {$limitWhereClause} AND {$repeatEventClause}
1138 {$groupByClause}
1139 {$havingClause}";
1140
1141 $valsqlInsertValues = CRM_Core_DAO::executeQuery($sqlInsertValues, array(1 => array($actionSchedule->id, 'Integer')));
1142
1143 $arrValues = array();
1144 while ($valsqlInsertValues->fetch()) {
1145 $arrValues[] = "( {$valsqlInsertValues->contact_id}, {$valsqlInsertValues->entity_id}, '{$valsqlInsertValues->entity_table}',{$valsqlInsertValues->action_schedule_id} )";
1146 }
1147
1148 $valString = implode(',', $arrValues);
1149
1150 if ($valString) {
1151 $query = '
1152 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1153 CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer')));
1154 }
1155
1156 if ($limitTo == 0) {
1157 $addSelect .= ', MAX(reminder.action_date_time) as latest_log_time';
1158 $sqlEndEventCheck = "
1159 SELECT * FROM {$table}
1160 {$whereClause} AND {$repeatEventClause} LIMIT 1";
1161
1162 $daoCheck = CRM_Core_DAO::executeQuery($sqlEndEventCheck);
1163 if ($daoCheck->fetch()) {
1164 $valSqlAdditionInsert = "
1165 {$addSelect}
1166 FROM {$contactTable}
1167 {$addGroup}
1168 INNER JOIN {$additionReminderClause}
1169 WHERE {$addWhere} AND c.is_deleted = 0 AND c.is_deceased = 0
1170 GROUP BY reminder.contact_id
1171 {$havingClause}
1172 ";
1173 $daoForVals = CRM_Core_DAO::executeQuery($valSqlAdditionInsert);
1174 $addValues = array();
1175 while ($daoForVals->fetch()) {
1176 $addValues[] = "( {$daoForVals->contact_id}, {$daoForVals->entity_id}, '{$daoForVals->entity_table}',{$daoForVals->action_schedule_id} )";
1177 }
1178 $valString = implode(',', $addValues);
1179
1180 if ($valString) {
1181 $query = '
1182 INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES ' . $valString;
1183 CRM_Core_DAO::executeQuery($query);
1184 }
1185 }
1186 }
1187 }
1188 }
1189 }
1190
1191 static function permissionedRelationships($field) {
1192 $query = '
1193 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
1194 FROM civicrm_membership m
1195 LEFT JOIN civicrm_membership cm ON cm.id = m.owner_membership_id
1196 LEFT JOIN civicrm_membership_type cmt ON cmt.id = m.membership_type_id
1197 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 )
1198 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 ) )
1199 WHERE m.owner_membership_id IS NOT NULL AND
1200 ( rel.is_permission_a_b = 0 OR rel.is_permission_b_a = 0)
1201
1202 ';
1203 $excludeIds = array();
1204 $dao = CRM_Core_DAO::executeQuery($query, array());
1205 while ($dao->fetch()) {
1206 if ($dao->slave_contact == $dao->contact_id_a && $dao->is_permission_b_a == 0) {
1207 $excludeIds[] = $dao->slave_contact;
1208 }
1209 elseif ($dao->slave_contact == $dao->contact_id_b && $dao->is_permission_a_b == 0) {
1210 $excludeIds[] = $dao->slave_contact;
1211 }
1212 }
1213
1214 if (!empty($excludeIds)) {
1215 $clause = "AND {$field} NOT IN ( " .implode(', ', $excludeIds) . ' ) ';
1216 return $clause;
1217 }
1218 return NULL;
1219 }
1220
1221 static function processQueue($now = NULL, $params = array()) {
1222 $now = $now ? CRM_Utils_Time::setTime($now) : CRM_Utils_Time::getTime();
1223
1224 $mappings = self::getMapping();
1225 foreach ($mappings as $mappingID => $mapping) {
1226 self::buildRecipientContacts($mappingID, $now, $params);
1227 self::sendMailings($mappingID, $now);
1228 }
1229
1230 $result = array(
1231 'is_error' => 0,
1232 'messages' => ts('Sent all scheduled reminders successfully'),
1233 );
1234 return $result;
1235 }
1236
1237 static function isConfigured($id, $mappingID) {
1238 $queryString = "SELECT count(id) FROM civicrm_action_schedule
1239 WHERE mapping_id = %1 AND
1240 entity_value = %2";
1241
1242 $params = array(
1243 1 => array($mappingID, 'Integer'),
1244 2 => array($id, 'Integer'),
1245 );
1246 return CRM_Core_DAO::singleValueQuery($queryString, $params);
1247 }
1248
1249 static function getRecipientListing($mappingID, $recipientType) {
1250 $options = array();
1251 if (!$mappingID || !$recipientType) {
1252 return $options;
1253 }
1254
1255 $mapping = self::getMapping($mappingID);
1256
1257 switch ($mapping['entity']) {
1258 case 'civicrm_participant':
1259 $eventContacts = CRM_Core_OptionGroup::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1260 if (empty($eventContacts[$recipientType])) {
1261 return $options;
1262 }
1263 if ($eventContacts[$recipientType] == 'participant_role') {
1264 $options = CRM_Event_PseudoConstant::participantRole();
1265 }
1266 break;
1267 }
1268
1269 return $options;
1270 }
1271 }
1272