/**
  * Execute the default schedule, without any special recipient selections.
  *
  * @dataProvider createTestCases
  *
  * @param string $targetDate
  * @param string $setupFuncs
  * @param array $expectMessages
  *
  * @throws \Exception
  */
 public function testDefault($targetDate, $setupFuncs, $expectMessages)
 {
     $this->targetDate = $targetDate;
     foreach (explode(' ', $setupFuncs) as $setupFunc) {
         $this->{$setupFunc}();
     }
     $this->schedule->save();
     $actualMessages = array();
     foreach ($this->cronTimes() as $time) {
         \CRM_Utils_Time::setTime($time);
         $this->callAPISuccess('job', 'send_reminder', array());
         foreach ($this->mut->getAllMessages('ezc') as $message) {
             /** @var \ezcMail $message */
             $simpleMessage = array('time' => $time, 'to' => \CRM_Utils_Array::collect('email', $message->to), 'subject' => $message->subject);
             sort($simpleMessage['to']);
             $actualMessages[] = $simpleMessage;
             $this->mut->clearMessages();
         }
     }
     $errorText = "Incorrect messages: " . print_r(array('actualMessages' => $actualMessages, 'expectMessages' => $expectMessages), 1);
     $this->assertEquals(count($expectMessages), count($actualMessages), $errorText);
     usort($expectMessages, array(__CLASS__, 'compareSimpleMsgs'));
     usort($actualMessages, array(__CLASS__, 'compareSimpleMsgs'));
     foreach ($expectMessages as $offset => $expectMessage) {
         $actualMessage = $actualMessages[$offset];
         $this->assertApproxEquals(strtotime($expectMessage['time']), strtotime($actualMessage['time']), $this->dateTolerance, $errorText);
         if (isset($expectMessage['to'])) {
             sort($expectMessage['to']);
             $this->assertEquals($expectMessage['to'], $actualMessage['to'], $errorText);
         }
         if (isset($expectMessage['subject'])) {
             $this->assertRegExp($expectMessage['subject'], $actualMessage['subject'], $errorText);
         }
     }
 }
 /**
  * @param array $values
  *   The submitted form values.
  * @return CRM_Core_DAO_ActionSchedule
  */
 public function parseActionSchedule($values)
 {
     $params = array();
     $keys = array('title', 'subject', 'absolute_date', 'group_id', 'record_activity', 'limit_to', 'mode', 'sms_provider_id', 'from_name', 'from_email');
     foreach ($keys as $key) {
         $params[$key] = CRM_Utils_Array::value($key, $values);
     }
     $params['is_repeat'] = CRM_Utils_Array::value('is_repeat', $values, 0);
     $moreKeys = array('start_action_offset', 'start_action_unit', 'start_action_condition', 'start_action_date', 'repetition_frequency_unit', 'repetition_frequency_interval', 'end_frequency_unit', 'end_frequency_interval', 'end_action', 'end_date');
     if ($absoluteDate = CRM_Utils_Array::value('absolute_date', $params)) {
         $params['absolute_date'] = CRM_Utils_Date::processDate($absoluteDate);
         $params['is_repeat'] = 0;
         foreach ($moreKeys as $mkey) {
             $params[$mkey] = 'null';
         }
     } else {
         $params['absolute_date'] = 'null';
         foreach ($moreKeys as $mkey) {
             $params[$mkey] = CRM_Utils_Array::value($mkey, $values);
         }
     }
     $params['body_text'] = CRM_Utils_Array::value('text_message', $values);
     $params['sms_body_text'] = CRM_Utils_Array::value('sms_text_message', $values);
     $params['body_html'] = CRM_Utils_Array::value('html_message', $values);
     if (CRM_Utils_Array::value('recipient', $values) == 'manual') {
         $params['recipient_manual'] = CRM_Utils_Array::value('recipient_manual_id', $values);
         $params['group_id'] = $params['recipient'] = $params['recipient_listing'] = 'null';
     } elseif (CRM_Utils_Array::value('recipient', $values) == 'group') {
         $params['group_id'] = $values['group_id'];
         $params['recipient_manual'] = $params['recipient'] = $params['recipient_listing'] = 'null';
     } elseif (isset($values['recipient_listing']) && isset($values['limit_to']) && !CRM_Utils_System::isNull($values['recipient_listing']) && !CRM_Utils_System::isNull($values['limit_to'])) {
         $params['recipient'] = CRM_Utils_Array::value('recipient', $values);
         $params['recipient_listing'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Utils_Array::value('recipient_listing', $values));
         $params['group_id'] = $params['recipient_manual'] = 'null';
     } else {
         $params['recipient'] = CRM_Utils_Array::value('recipient', $values);
         $params['group_id'] = $params['recipient_manual'] = $params['recipient_listing'] = 'null';
     }
     if (!empty($this->_mappingID) && !empty($this->_compId)) {
         $params['mapping_id'] = $this->_mappingID;
         $params['entity_value'] = $this->_compId;
         $params['entity_status'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $values['entity']);
     } else {
         $params['mapping_id'] = $values['entity'][0];
         if ($params['mapping_id'] == 1) {
             $params['limit_to'] = 1;
         }
         $entity_value = CRM_Utils_Array::value(1, $values['entity'], array());
         $entity_status = CRM_Utils_Array::value(2, $values['entity'], array());
         $params['entity_value'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $entity_value);
         $params['entity_status'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $entity_status);
     }
     $params['is_active'] = CRM_Utils_Array::value('is_active', $values, 0);
     if (CRM_Utils_Array::value('is_repeat', $values) == 0) {
         $params['repetition_frequency_unit'] = 'null';
         $params['repetition_frequency_interval'] = 'null';
         $params['end_frequency_unit'] = 'null';
         $params['end_frequency_interval'] = 'null';
         $params['end_action'] = 'null';
         $params['end_date'] = 'null';
     }
     // multilingual options
     $params['filter_contact_language'] = CRM_Utils_Array::value('filter_contact_language', $values, array());
     $params['filter_contact_language'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $params['filter_contact_language']);
     $params['communication_language'] = CRM_Utils_Array::value('communication_language', $values, NULL);
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $params['id'] = $this->_id;
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         // we do this only once, so name never changes
         $params['name'] = CRM_Utils_String::munge($params['title'], '_', 64);
     }
     $modePrefixes = array('Mail' => NULL, 'SMS' => 'SMS');
     if ($params['mode'] == 'Email' || empty($params['sms_provider_id'])) {
         unset($modePrefixes['SMS']);
     } elseif ($params['mode'] == 'SMS') {
         unset($modePrefixes['Mail']);
     }
     //TODO: handle postprocessing of SMS and/or Email info based on $modePrefixes
     $composeFields = array('template', 'saveTemplate', 'updateTemplate', 'saveTemplateName');
     $msgTemplate = NULL;
     //mail template is composed
     foreach ($modePrefixes as $prefix) {
         $composeParams = array();
         foreach ($composeFields as $key) {
             $key = $prefix . $key;
             if (!empty($values[$key])) {
                 $composeParams[$key] = $values[$key];
             }
         }
         if (!empty($composeParams[$prefix . 'updateTemplate'])) {
             $templateParams = array('is_active' => TRUE);
             if ($prefix == 'SMS') {
                 $templateParams += array('msg_text' => $params['sms_body_text'], 'is_sms' => TRUE);
             } else {
                 $templateParams += array('msg_text' => $params['body_text'], 'msg_html' => $params['body_html'], 'msg_subject' => $params['subject']);
             }
             $templateParams['id'] = $values[$prefix . 'template'];
             $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams);
         }
         if (!empty($composeParams[$prefix . 'saveTemplate'])) {
             $templateParams = array('is_active' => TRUE);
             if ($prefix == 'SMS') {
                 $templateParams += array('msg_text' => $params['sms_body_text'], 'is_sms' => TRUE);
             } else {
                 $templateParams += array('msg_text' => $params['body_text'], 'msg_html' => $params['body_html'], 'msg_subject' => $params['subject']);
             }
             $templateParams['msg_title'] = $composeParams[$prefix . 'saveTemplateName'];
             $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams);
         }
         if ($prefix == 'SMS') {
             if (isset($msgTemplate->id)) {
                 $params['sms_template_id'] = $msgTemplate->id;
             } else {
                 $params['sms_template_id'] = CRM_Utils_Array::value('SMStemplate', $values);
             }
         } else {
             if (isset($msgTemplate->id)) {
                 $params['msg_template_id'] = $msgTemplate->id;
             } else {
                 $params['msg_template_id'] = CRM_Utils_Array::value('template', $values);
             }
         }
     }
     $actionSchedule = new CRM_Core_DAO_ActionSchedule();
     $actionSchedule->copyValues($params);
     return $actionSchedule;
 }
    /**
     * @param $mappingID
     * @param $now
     *
     * @throws CRM_Core_Exception
     */
    static function sendMailings($mappingID, $now)
    {
        $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
        $fromEmailAddress = "{$domainValues['0']} <{$domainValues['1']}>";
        $mapping = new CRM_Core_DAO_ActionMapping();
        $mapping->id = $mappingID;
        $mapping->find(TRUE);
        $actionSchedule = new CRM_Core_DAO_ActionSchedule();
        $actionSchedule->mapping_id = $mappingID;
        $actionSchedule->is_active = 1;
        $actionSchedule->find(FALSE);
        $tokenFields = array();
        $session = CRM_Core_Session::singleton();
        while ($actionSchedule->fetch()) {
            $extraSelect = $extraJoin = $extraWhere = $extraOn = '';
            if ($actionSchedule->from_email) {
                $fromEmailAddress = "{$actionSchedule->from_name} <{$actionSchedule->from_email}>";
            }
            if ($actionSchedule->record_activity) {
                if ($mapping->entity == 'civicrm_membership') {
                    $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Membership Renewal Reminder', 'name');
                } else {
                    $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Reminder Sent', 'name');
                }
                $activityStatusID = CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name');
            }
            if ($mapping->entity == 'civicrm_activity') {
                $tokenEntity = 'activity';
                $tokenFields = array('activity_id', 'activity_type', 'subject', 'details', 'activity_date_time');
                $extraSelect = ', ov.label as activity_type, e.id as activity_id';
                $extraJoin = "\nINNER JOIN civicrm_option_group og ON og.name = 'activity_type'\nINNER JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
                $extraOn = ' AND e.is_current_revision = 1 AND e.is_deleted = 0 ';
                if ($actionSchedule->limit_to == 0) {
                    $extraJoin = "\nLEFT JOIN civicrm_option_group og ON og.name = 'activity_type'\nLEFT JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id";
                }
            }
            if ($mapping->entity == 'civicrm_participant') {
                $tokenEntity = 'event';
                $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');
                $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 ';
                $extraJoin = "\nINNER JOIN civicrm_event ev ON e.event_id = ev.id\nINNER JOIN civicrm_option_group og ON og.name = 'event_type'\nINNER JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id\nLEFT  JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id\nLEFT  JOIN civicrm_address address ON address.id = lb.address_id\nLEFT  JOIN civicrm_email email ON email.id = lb.email_id\nLEFT  JOIN civicrm_phone phone ON phone.id = lb.phone_id\n";
                if ($actionSchedule->limit_to == 0) {
                    $extraJoin = "\nLEFT JOIN civicrm_event ev ON e.event_id = ev.id\nLEFT JOIN civicrm_option_group og ON og.name = 'event_type'\nLEFT JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id\nLEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id\nLEFT JOIN civicrm_address address ON address.id = lb.address_id\nLEFT JOIN civicrm_email email ON email.id = lb.email_id\nLEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id\n";
                }
            }
            if ($mapping->entity == 'civicrm_membership') {
                $tokenEntity = 'membership';
                $tokenFields = array('fee', 'id', 'join_date', 'start_date', 'end_date', 'status', 'type');
                $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';
                $extraJoin = '
 INNER JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
 INNER JOIN civicrm_membership_status ms ON e.status_id = ms.id';
                if ($actionSchedule->limit_to == 0) {
                    $extraJoin = '
 LEFT JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id
 LEFT JOIN civicrm_membership_status ms ON e.status_id = ms.id';
                }
            }
            if ($mapping->entity == 'civicrm_contact') {
                $tokenEntity = 'contact';
                //TODO: get full list somewhere!
                $tokenFields = array('birth_date', 'last_name');
                //TODO: is there anything to add here?
            }
            $entityJoinClause = "INNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
            if ($actionSchedule->limit_to == 0) {
                $entityJoinClause = "LEFT JOIN {$mapping->entity} e ON e.id = reminder.entity_id";
                $extraWhere .= " AND (e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact')";
            }
            $entityJoinClause .= $extraOn;
            $query = "\nSELECT reminder.id as reminderID, reminder.contact_id as contactID, reminder.*, e.id as entityID, e.* {$extraSelect}\nFROM  civicrm_action_log reminder\n{$entityJoinClause}\n{$extraJoin}\nWHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL\n{$extraWhere}";
            $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer')));
            while ($dao->fetch()) {
                $entityTokenParams = array();
                foreach ($tokenFields as $field) {
                    if ($field == 'location') {
                        $loc = array();
                        $stateProvince = CRM_Core_PseudoConstant::stateProvince();
                        $loc['street_address'] = $dao->street_address;
                        $loc['city'] = $dao->city;
                        $loc['state_province'] = CRM_Utils_Array::value($dao->state_province_id, $stateProvince);
                        $loc['postal_code'] = $dao->postal_code;
                        $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address::format($loc);
                    } elseif ($field == 'info_url') {
                        $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE);
                    } elseif ($field == 'registration_url') {
                        $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE);
                    } elseif (in_array($field, array('start_date', 'end_date', 'join_date', 'activity_date_time'))) {
                        $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date::customFormat($dao->{$field});
                    } elseif ($field == 'balance') {
                        $info = CRM_Contribute_BAO_Contribution::getPaymentInfo($dao->entityID, 'event');
                        $balancePay = CRM_Utils_Array::value('balance', $info);
                        $balancePay = CRM_Utils_Money::format($balancePay);
                        $entityTokenParams["{$tokenEntity}." . $field] = $balancePay;
                    } elseif ($field == 'fee_amount') {
                        $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Money::format($dao->{$field});
                    } else {
                        $entityTokenParams["{$tokenEntity}." . $field] = $dao->{$field};
                    }
                }
                $isError = 0;
                $errorMsg = $toEmail = $toPhoneNumber = '';
                if ($actionSchedule->mode == 'SMS' or $actionSchedule->mode == 'User_Preference') {
                    $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0);
                    $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($dao->contactID, FALSE, 'Mobile', $filters);
                    //to get primary mobile ph,if not get a first mobile phONE
                    if (!empty($toPhoneNumbers)) {
                        $toPhoneNumberDetails = reset($toPhoneNumbers);
                        $toPhoneNumber = CRM_Utils_Array::value('phone', $toPhoneNumberDetails);
                        //contact allows to send sms
                        $toDoNotSms = 0;
                    }
                }
                if ($actionSchedule->mode == 'Email' or $actionSchedule->mode == 'User_Preference') {
                    $toEmail = CRM_Contact_BAO_Contact::getPrimaryEmail($dao->contactID);
                }
                if ($toEmail || !(empty($toPhoneNumber) or $toDoNotSms)) {
                    $to['email'] = $toEmail;
                    $to['phone'] = $toPhoneNumber;
                    $result = CRM_Core_BAO_ActionSchedule::sendReminder($dao->contactID, $to, $actionSchedule->id, $fromEmailAddress, $entityTokenParams);
                    if (!$result || is_a($result, 'PEAR_Error')) {
                        // we could not send an email, for now we ignore, CRM-3406
                        $isError = 1;
                    }
                } else {
                    $isError = 1;
                    $errorMsg = "Couldn\\'t find recipient\\'s email address.";
                }
                // update action log record
                $logParams = array('id' => $dao->reminderID, 'is_error' => $isError, 'message' => $errorMsg ? $errorMsg : "null", 'action_date_time' => $now);
                CRM_Core_BAO_ActionLog::create($logParams);
                // insert activity log record if needed
                if ($actionSchedule->record_activity) {
                    $activityParams = array('subject' => $actionSchedule->title, 'details' => $actionSchedule->body_html, 'source_contact_id' => $session->get('userID') ? $session->get('userID') : $dao->contactID, 'target_contact_id' => $dao->contactID, 'activity_date_time' => date('YmdHis'), 'status_id' => $activityStatusID, 'activity_type_id' => $activityTypeID, 'source_record_id' => $dao->entityID);
                    $activity = CRM_Activity_BAO_Activity::create($activityParams);
                }
            }
            $dao->free();
        }
    }
Esempio n. 4
0
 /**
  * Returns the list of fields that can be exported
  *
  * @param bool $prefix
  *
  * @return array
  */
 static function &export($prefix = false)
 {
     if (!self::$_export) {
         self::$_export = array();
         $fields = self::fields();
         foreach ($fields as $name => $field) {
             if (CRM_Utils_Array::value('export', $field)) {
                 if ($prefix) {
                     self::$_export['action_schedule'] =& $fields[$name];
                 } else {
                     self::$_export[$name] =& $fields[$name];
                 }
             }
         }
     }
     return self::$_export;
 }
 /**
  * @param int $mappingID
  * @param $now
  *
  * @throws CRM_Core_Exception
  */
 public static function sendMailings($mappingID, $now)
 {
     $mapping = CRM_Utils_Array::first(self::getMappings(array('id' => $mappingID)));
     $actionSchedule = new CRM_Core_DAO_ActionSchedule();
     $actionSchedule->mapping_id = $mappingID;
     $actionSchedule->is_active = 1;
     $actionSchedule->find(FALSE);
     while ($actionSchedule->fetch()) {
         $query = CRM_Core_BAO_ActionSchedule::prepareMailingQuery($mapping, $actionSchedule);
         $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer')));
         $multilingual = CRM_Core_I18n::isMultilingual();
         while ($dao->fetch()) {
             // switch language if necessary
             if ($multilingual) {
                 $preferred_language = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $dao->contactID, 'preferred_language');
                 CRM_Core_BAO_ActionSchedule::setCommunicationLanguage($actionSchedule->communication_language, $preferred_language);
             }
             $errors = array();
             try {
                 $tokenProcessor = self::createTokenProcessor($actionSchedule, $mapping);
                 $tokenProcessor->addRow()->context('contactId', $dao->contactID)->context('actionSearchResult', (object) $dao->toArray());
                 foreach ($tokenProcessor->evaluate()->getRows() as $tokenRow) {
                     if ($actionSchedule->mode == 'SMS' or $actionSchedule->mode == 'User_Preference') {
                         CRM_Utils_Array::extend($errors, self::sendReminderSms($tokenRow, $actionSchedule, $dao->contactID));
                     }
                     if ($actionSchedule->mode == 'Email' or $actionSchedule->mode == 'User_Preference') {
                         CRM_Utils_Array::extend($errors, self::sendReminderEmail($tokenRow, $actionSchedule, $dao->contactID));
                     }
                 }
             } catch (\Civi\Token\TokenException $e) {
                 $errors['token_exception'] = $e->getMessage();
             }
             // update action log record
             $logParams = array('id' => $dao->reminderID, 'is_error' => !empty($errors), 'message' => empty($errors) ? "null" : implode(' ', $errors), 'action_date_time' => $now);
             CRM_Core_BAO_ActionLog::create($logParams);
             // insert activity log record if needed
             if ($actionSchedule->record_activity && empty($errors)) {
                 $caseID = empty($dao->case_id) ? NULL : $dao->case_id;
                 CRM_Core_BAO_ActionSchedule::createMailingActivity($actionSchedule, $mapping, $dao->contactID, $dao->entityID, $caseID);
             }
         }
         $dao->free();
     }
 }
 static function buildRecipientContacts($mappingID, $now)
 {
     $actionSchedule = new CRM_Core_DAO_ActionSchedule();
     $actionSchedule->mapping_id = $mappingID;
     $actionSchedule->is_active = 1;
     $actionSchedule->find();
     while ($actionSchedule->fetch()) {
         $mapping = new CRM_Core_DAO_ActionMapping();
         $mapping->id = $mappingID;
         $mapping->find(TRUE);
         $select = $join = $where = array();
         $value = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($actionSchedule->entity_value, CRM_Core_DAO::VALUE_SEPARATOR));
         $value = implode(',', $value);
         $status = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($actionSchedule->entity_status, CRM_Core_DAO::VALUE_SEPARATOR));
         $status = implode(',', $status);
         if (!CRM_Utils_System::isNull($mapping->entity_recipient)) {
             $recipientOptions = CRM_Core_OptionGroup::values($mapping->entity_recipient);
         }
         $from = "{$mapping->entity} e";
         if ($mapping->entity == 'civicrm_activity') {
             switch ($recipientOptions[$actionSchedule->recipient]) {
                 case 'Activity Assignees':
                     $contactField = "r.assignee_contact_id";
                     $join[] = "INNER JOIN civicrm_activity_assignment r ON  r.activity_id = e.id";
                     break;
                 case 'Activity Source':
                     $contactField = "e.source_contact_id";
                     break;
                 case 'Activity Targets':
                     $contactField = "r.target_contact_id";
                     $join[] = "INNER JOIN civicrm_activity_target r ON  r.activity_id = e.id";
                     break;
                 default:
                     break;
             }
             // build where clause
             if (!empty($value)) {
                 $where[] = "e.activity_type_id IN ({$value})";
             }
             if (!empty($status)) {
                 $where[] = "e.status_id IN ({$status})";
             }
             $where[] = " e.is_current_revision = 1 ";
             $where[] = " e.is_deleted = 0 ";
             $dateField = 'e.activity_date_time';
         }
         if ($mapping->entity == 'civicrm_participant') {
             $contactField = "e.contact_id";
             $join[] = "INNER JOIN civicrm_event r ON e.event_id = r.id";
             if ($actionSchedule->recipient_listing) {
                 $rList = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($actionSchedule->recipient_listing, CRM_Core_DAO::VALUE_SEPARATOR));
                 $rList = implode(',', $rList);
                 switch ($recipientOptions[$actionSchedule->recipient]) {
                     case 'Participant Role':
                         $where[] = "e.role_id IN ({$rList})";
                         break;
                     default:
                         break;
                 }
             }
             // build where clause
             if (!empty($value)) {
                 $where[] = $mapping->entity_value == 'event_type' ? "r.event_type_id IN ({$value})" : "r.id IN ({$value})";
             }
             if (!empty($status)) {
                 $where[] = "e.status_id IN ({$status})";
             }
             $where[] = "r.is_active = 1";
             $dateField = str_replace('event_', 'r.', $actionSchedule->start_action_date);
         }
         $notINClause = '';
         if ($mapping->entity == 'civicrm_membership') {
             $contactField = "e.contact_id";
             // build where clause
             if ($status == 2) {
                 //auto-renew memberships
                 $where[] = "e.contribution_recur_id IS NOT NULL ";
             } elseif ($status == 1) {
                 $where[] = "e.contribution_recur_id IS NULL ";
             }
             // build where clause
             if (!empty($value)) {
                 $where[] = "e.membership_type_id IN ({$value})";
             }
             $dateField = str_replace('membership_', 'e.', $actionSchedule->start_action_date);
             $notINClause = self::permissionedRelationships($contactField);
         }
         if ($actionSchedule->group_id) {
             $join[] = "INNER JOIN civicrm_group_contact grp ON {$contactField} = grp.contact_id AND grp.status = 'Added'";
             $where[] = "grp.group_id IN ({$actionSchedule->group_id})";
         } elseif (!empty($actionSchedule->recipient_manual)) {
             $rList = CRM_Utils_Type::escape($actionSchedule->recipient_manual, 'String');
             $where[] = "{$contactField} IN ({$rList})";
         }
         $select[] = "{$contactField} as contact_id";
         $select[] = "e.id as entity_id";
         $select[] = "'{$mapping->entity}' as entity_table";
         $select[] = "{$actionSchedule->id} as action_schedule_id";
         $reminderJoinClause = "civicrm_action_log reminder ON reminder.contact_id = {$contactField} AND\nreminder.entity_id          = e.id AND\nreminder.entity_table       = '{$mapping->entity}' AND\nreminder.action_schedule_id = %1";
         $join[] = "INNER JOIN civicrm_contact c ON c.id = {$contactField}";
         $where[] = "c.is_deleted = 0";
         if ($actionSchedule->start_action_date) {
             $startDateClause = array();
             $op = $actionSchedule->start_action_condition == 'before' ? "<=" : ">=";
             $operator = $actionSchedule->start_action_condition == 'before' ? "DATE_SUB" : "DATE_ADD";
             $date = $operator . "({$dateField}, INTERVAL {$actionSchedule->start_action_offset} {$actionSchedule->start_action_unit})";
             $startDateClause[] = "'{$now}' >= {$date}";
             if ($mapping->entity == 'civicrm_participant') {
                 $startDateClause[] = $operator . "({$now}, INTERVAL 1 DAY ) {$op} " . $dateField;
             } else {
                 $startDateClause[] = "DATE_SUB({$now}, INTERVAL 1 DAY ) <= {$date}";
             }
             $startDate = implode(' AND ', $startDateClause);
         } elseif ($actionSchedule->absolute_date) {
             $startDate = "DATEDIFF(DATE('{$now}'),'{$actionSchedule->absolute_date}') = 0";
         }
         // ( now >= date_built_from_start_time ) OR ( now = absolute_date )
         $dateClause = "reminder.id IS NULL AND {$startDate}";
         // start composing query
         $selectClause = "SELECT " . implode(', ', $select);
         $fromClause = "FROM {$from}";
         $joinClause = !empty($join) ? implode(' ', $join) : '';
         $whereClause = "WHERE " . implode(' AND ', $where);
         $query = "\nINSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id)\n{$selectClause}\n{$fromClause}\n{$joinClause}\nLEFT JOIN {$reminderJoinClause}\n{$whereClause} AND {$dateClause} {$notINClause}";
         CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer')));
         // if repeat is turned ON:
         if ($actionSchedule->is_repeat) {
             $repeatEvent = ($actionSchedule->end_action == 'before' ? "DATE_SUB" : "DATE_ADD") . "({$dateField}, INTERVAL {$actionSchedule->end_frequency_interval} {$actionSchedule->end_frequency_unit})";
             if ($actionSchedule->repetition_frequency_unit == 'day') {
                 $hrs = 24 * $actionSchedule->repetition_frequency_interval;
             } elseif ($actionSchedule->repetition_frequency_unit == 'week') {
                 $hrs = 24 * $actionSchedule->repetition_frequency_interval * 7;
             } else {
                 $hrs = $actionSchedule->repetition_frequency_interval;
             }
             // (now <= repeat_end_time )
             $repeatEventClause = "'{$now}' <= {$repeatEvent}";
             // diff(now && logged_date_time) >= repeat_interval
             $havingClause = "HAVING TIMEDIFF({$now}, latest_log_time) >= TIME('{$hrs}:00:00')";
             $groupByClause = "GROUP BY reminder.contact_id, reminder.entity_id, reminder.entity_table";
             $selectClause .= ", MAX(reminder.action_date_time) as latest_log_time";
             $sqlInsertValues = "{$selectClause}\n{$fromClause}\n{$joinClause}\nINNER JOIN {$reminderJoinClause}\n{$whereClause} AND {$repeatEventClause}\n{$groupByClause}\n{$havingClause}";
             $valsqlInsertValues = CRM_Core_DAO::executeQuery($sqlInsertValues, array(1 => array($actionSchedule->id, 'Integer')));
             $arrValues = array();
             while ($valsqlInsertValues->fetch()) {
                 $arrValues[] = "( {$valsqlInsertValues->contact_id}, {$valsqlInsertValues->entity_id}, '{$valsqlInsertValues->entity_table}',{$valsqlInsertValues->action_schedule_id} )";
             }
             $valString = implode(',', $arrValues);
             if ($valString) {
                 $query = "\n              INSERT INTO civicrm_action_log (contact_id, entity_id, entity_table, action_schedule_id) VALUES " . $valString;
                 CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer')));
             }
         }
     }
 }
Esempio n. 7
0
 /**
  * adds $value['foo_display'] for each $value['foo'] enum from civicrm_action_schedule
  *
  * @param array $values (reference)  the array up for enhancing
  * @return void
  */
 static function addDisplayEnums(&$values)
 {
     $enumFields =& CRM_Core_DAO_ActionSchedule::getEnums();
     foreach ($enumFields as $enum) {
         if (isset($values[$enum])) {
             $values[$enum . '_display'] = CRM_Core_DAO_ActionSchedule::tsEnum($enum, $values[$enum]);
         }
     }
 }