/**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values)
 {
     try {
         // first make sure this is a valid line
         $response = $this->summary($values);
         if ($response != CRM_Import_Parser::VALID) {
             return $response;
         }
         $params =& $this->getActiveFieldParams();
         //assign join date equal to start date if join date is not provided
         if (!CRM_Utils_Array::value('join_date', $params) && CRM_Utils_Array::value('membership_start_date', $params)) {
             $params['join_date'] = $params['membership_start_date'];
         }
         $session = CRM_Core_Session::singleton();
         $dateType = $session->get('dateTypes');
         $formatted = array();
         $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
         // don't add to recent items, CRM-4399
         $formatted['skipRecentView'] = TRUE;
         $dateLabels = array('join_date' => ts('Member Since'), 'membership_start_date' => ts('Start Date'), 'membership_end_date' => ts('End Date'));
         foreach ($params as $key => $val) {
             if ($val) {
                 switch ($key) {
                     case 'join_date':
                     case 'membership_start_date':
                     case 'membership_end_date':
                         if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                             if (!CRM_Utils_Rule::date($params[$key])) {
                                 CRM_Contact_Import_Parser_Contact::addToErrorMsg($dateLabels[$key], $errorMessage);
                             }
                         } else {
                             CRM_Contact_Import_Parser_Contact::addToErrorMsg($dateLabels[$key], $errorMessage);
                         }
                         break;
                     case 'membership_type_id':
                         if (!is_numeric($val)) {
                             unset($params['membership_type_id']);
                             $params['membership_type'] = $val;
                         }
                         break;
                     case 'status_id':
                         if (!is_numeric($val)) {
                             unset($params['status_id']);
                             $params['membership_status'] = $val;
                         }
                         break;
                     case 'is_override':
                         $params[$key] = CRM_Utils_String::strtobool($val);
                         break;
                 }
                 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                     if ($customFields[$customFieldID]['data_type'] == 'Date') {
                         CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                         unset($params[$key]);
                     } else {
                         if ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                             $params[$key] = CRM_Utils_String::strtoboolstr($val);
                         }
                     }
                 }
             }
         }
         //date-Format part ends
         static $indieFields = NULL;
         if ($indieFields == NULL) {
             $tempIndieFields = CRM_Member_DAO_Membership::import();
             $indieFields = $tempIndieFields;
         }
         $formatValues = array();
         foreach ($params as $key => $field) {
             if ($field == NULL || $field === '') {
                 continue;
             }
             $formatValues[$key] = $field;
         }
         //format params to meet api v2 requirements.
         //@todo find a way to test removing this formatting
         $formatError = $this->membership_format_params($formatValues, $formatted, TRUE);
         if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) {
             $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, NULL, 'Membership');
         } else {
             //fix for CRM-2219 Update Membership
             // onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE
             if (CRM_Utils_Array::value('is_override', $formatted) && !CRM_Utils_Array::value('status_id', $formatted)) {
                 array_unshift($values, 'Required parameter missing: Status');
                 return CRM_Import_Parser::ERROR;
             }
             if (!empty($formatValues['membership_id'])) {
                 $dao = new CRM_Member_BAO_Membership();
                 $dao->id = $formatValues['membership_id'];
                 $dates = array('join_date', 'start_date', 'end_date');
                 foreach ($dates as $v) {
                     if (!CRM_Utils_Array::value($v, $formatted)) {
                         $formatted[$v] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $formatValues['membership_id'], $v);
                     }
                 }
                 $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, $formatValues['membership_id'], 'Membership');
                 if ($dao->find(TRUE)) {
                     $ids = array('membership' => $formatValues['membership_id'], 'userId' => $session->get('userID'));
                     $newMembership = CRM_Member_BAO_Membership::create($formatted, $ids, TRUE);
                     if (civicrm_error($newMembership)) {
                         array_unshift($values, $newMembership['is_error'] . ' for Membership ID ' . $formatValues['membership_id'] . '. Row was skipped.');
                         return CRM_Import_Parser::ERROR;
                     } else {
                         $this->_newMemberships[] = $newMembership->id;
                         return CRM_Import_Parser::VALID;
                     }
                 } else {
                     array_unshift($values, 'Matching Membership record not found for Membership ID ' . $formatValues['membership_id'] . '. Row was skipped.');
                     return CRM_Import_Parser::ERROR;
                 }
             }
         }
         //Format dates
         $startDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $formatted), '%Y-%m-%d');
         $endDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $formatted), '%Y-%m-%d');
         $joinDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $formatted), '%Y-%m-%d');
         if ($this->_contactIdIndex < 0) {
             //retrieve contact id using contact dedupe rule
             $formatValues['contact_type'] = $this->_contactType;
             $formatValues['version'] = 3;
             require_once 'CRM/Utils/DeprecatedUtils.php';
             $error = _civicrm_api3_deprecated_check_contact_dedupe($formatValues);
             if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
                 $matchedIDs = explode(',', $error['error_message']['params'][0]);
                 if (count($matchedIDs) > 1) {
                     array_unshift($values, 'Multiple matching contact records detected for this row. The membership was not imported');
                     return CRM_Import_Parser::ERROR;
                 } else {
                     $cid = $matchedIDs[0];
                     $formatted['contact_id'] = $cid;
                     //fix for CRM-1924
                     $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate);
                     self::formattedDates($calcDates, $formatted);
                     //fix for CRM-3570, exclude the statuses those having is_admin = 1
                     //now user can import is_admin if is override is true.
                     $excludeIsAdmin = FALSE;
                     if (!CRM_Utils_Array::value('is_override', $formatted)) {
                         $formatted['exclude_is_admin'] = $excludeIsAdmin = TRUE;
                     }
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin, $formatted['membership_type_id'], $formatted);
                     if (!CRM_Utils_Array::value('status_id', $formatted)) {
                         $formatted['status_id'] = $calcStatus['id'];
                     } elseif (!CRM_Utils_Array::value('is_override', $formatted)) {
                         if (empty($calcStatus)) {
                             array_unshift($values, 'Status in import row (' . $formatValues['status_id'] . ') does not match calculated status based on your configured Membership Status Rules. Record was not imported.');
                             return CRM_Import_Parser::ERROR;
                         } elseif ($formatted['status_id'] != $calcStatus['id']) {
                             //Status Hold" is either NOT mapped or is FALSE
                             array_unshift($values, 'Status in import row (' . $formatValues['status_id'] . ') does not match calculated status based on your configured Membership Status Rules (' . $calcStatus['name'] . '). Record was not imported.');
                             return CRM_Import_Parser::ERROR;
                         }
                     }
                     $newMembership = civicrm_api3('membership', 'create', $formatted);
                     $this->_newMemberships[] = $newMembership['id'];
                     return CRM_Import_Parser::VALID;
                 }
             } else {
                 // Using new Dedupe rule.
                 $ruleParams = array('contact_type' => $this->_contactType, 'used' => 'Unsupervised');
                 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
                 $disp = '';
                 foreach ($fieldsArray as $value) {
                     if (array_key_exists(trim($value), $params)) {
                         $paramValue = $params[trim($value)];
                         if (is_array($paramValue)) {
                             $disp .= $params[trim($value)][0][trim($value)] . " ";
                         } else {
                             $disp .= $params[trim($value)] . " ";
                         }
                     }
                 }
                 if (CRM_Utils_Array::value('external_identifier', $params)) {
                     if ($disp) {
                         $disp .= "AND {$params['external_identifier']}";
                     } else {
                         $disp = $params['external_identifier'];
                     }
                 }
                 array_unshift($values, 'No matching Contact found for (' . $disp . ')');
                 return CRM_Import_Parser::ERROR;
             }
         } else {
             if (CRM_Utils_Array::value('external_identifier', $formatValues)) {
                 $checkCid = new CRM_Contact_DAO_Contact();
                 $checkCid->external_identifier = $formatValues['external_identifier'];
                 $checkCid->find(TRUE);
                 if ($checkCid->id != $formatted['contact_id']) {
                     array_unshift($values, 'Mismatch of External identifier :' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
                     return CRM_Import_Parser::ERROR;
                 }
             }
             //to calculate dates
             $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate);
             self::formattedDates($calcDates, $formatted);
             //end of date calculation part
             //fix for CRM-3570, exclude the statuses those having is_admin = 1
             //now user can import is_admin if is override is true.
             $excludeIsAdmin = FALSE;
             if (!CRM_Utils_Array::value('is_override', $formatted)) {
                 $formatted['exclude_is_admin'] = $excludeIsAdmin = TRUE;
             }
             $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin, $formatted['membership_type_id'], $formatted);
             if (!CRM_Utils_Array::value('status_id', $formatted)) {
                 $formatted['status_id'] = CRM_Utils_Array::value('id', $calcStatus);
             } elseif (!CRM_Utils_Array::value('is_override', $formatted)) {
                 if (empty($calcStatus)) {
                     array_unshift($values, 'Status in import row (' . CRM_Utils_Array::value('status_id', $formatValues) . ') does not match calculated status based on your configured Membership Status Rules. Record was not imported.');
                     return CRM_Import_Parser::ERROR;
                 } elseif ($formatted['status_id'] != $calcStatus['id']) {
                     //Status Hold" is either NOT mapped or is FALSE
                     array_unshift($values, 'Status in import row (' . CRM_Utils_Array::value('status_id', $formatValues) . ') does not match calculated status based on your configured Membership Status Rules (' . $calcStatus['name'] . '). Record was not imported.');
                     return CRM_Import_Parser::ERROR;
                 }
             }
             $newMembership = civicrm_api3('membership', 'create', $formatted);
             $this->_newMemberships[] = $newMembership['id'];
             return CRM_Import_Parser::VALID;
         }
     } catch (Exception $e) {
         array_unshift($values, $e->getMessage());
         return CRM_Import_Parser::ERROR;
     }
 }
Example #2
0
 /**
  * Format Date params
  *
  * Although the api will accept any strtotime valid string CiviCRM accepts at least one date format
  * not supported by strtotime so we should run this through a conversion
  * @param unknown $params
  */
 function formatDateParams()
 {
     $session = CRM_Core_Session::singleton();
     $dateType = $session->get('dateTypes');
     $setDateFields = array_intersect_key($this->_params, array_flip($this->_dateFields));
     foreach ($setDateFields as $key => $value) {
         CRM_Utils_Date::convertToDefaultDate($this->_params, $dateType, $key);
         $this->_params[$key] = CRM_Utils_Date::processDate($this->_params[$key]);
     }
 }
Example #3
0
 /**
  * format common params data to proper format to store.
  *
  * @param array  $params        contain record values.
  * @param array  $formatted     array of formatted data.
  * @param array  $contactFields contact DAO fields.
  * @static
  */
 function formatCommonData($params, &$formatted, &$contactFields)
 {
     $csType = array(CRM_Utils_Array::value('contact_type', $formatted));
     //CRM-5125
     //add custom fields for contact sub type
     if (!empty($this->_contactSubType)) {
         $csType = $this->_contactSubType;
     }
     if ($relCsType = CRM_Utils_Array::value('contact_sub_type', $formatted)) {
         $csType = $relCsType;
     }
     $customFields = CRM_Core_BAO_CustomField::getFields($formatted['contact_type'], false, false, $csType);
     //if a Custom Email Greeting, Custom Postal Greeting or Custom Addressee is mapped, and no "Greeting / Addressee Type ID" is provided, then automatically set the type = Customized, CRM-4575
     $elements = array('email_greeting_custom' => 'email_greeting', 'postal_greeting_custom' => 'postal_greeting', 'addressee_custom' => 'addressee');
     foreach ($elements as $k => $v) {
         if (array_key_exists($k, $params) && !array_key_exists($v, $params)) {
             $label = key(CRM_Core_OptionGroup::values($v, true, null, null, 'AND v.name = "Customized"'));
             $params[$v] = $label;
         }
     }
     //format date first
     $session =& CRM_Core_Session::singleton();
     $dateType = $session->get("dateTypes");
     foreach ($params as $key => $val) {
         if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
             //we should not update Date to null, CRM-4062
             if ($val && $customFields[$customFieldID]['data_type'] == 'Date') {
                 self::formatCustomDate($params, $formatted, $dateType, $key);
                 unset($params[$key]);
             } else {
                 if ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                     $params[$key] = CRM_Utils_String::strtoboolstr($val);
                 }
             }
         }
         if ($key == 'birth_date' && $val) {
             CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
         } else {
             if ($key == 'deceased_date' && $val) {
                 CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
             } else {
                 if ($key == 'is_deceased' && $val) {
                     $params[$key] = CRM_Utils_String::strtoboolstr($val);
                 } else {
                     if ($key == 'gender') {
                         //CRM-4360
                         $params[$key] = $this->checkGender($val);
                     }
                 }
             }
         }
     }
     //now format custom data.
     foreach ($params as $key => $field) {
         if ($field == null || $field === '') {
             continue;
         }
         if (is_array($field)) {
             foreach ($field as $value) {
                 $break = false;
                 if (is_array($value)) {
                     foreach ($value as $name => $testForEmpty) {
                         // check if $value does not contain IM provider or phoneType
                         if (($name !== 'phone_type_id' || $name !== 'provider_id') && ($testForEmpty === '' || $testForEmpty == null)) {
                             $break = true;
                             break;
                         }
                     }
                 } else {
                     $break = true;
                 }
                 if (!$break) {
                     _civicrm_add_formatted_param($value, $formatted);
                 }
             }
             continue;
         }
         $formatValues = array($key => $field);
         if ($key !== 'preferred_communication_method' && array_key_exists($key, $contactFields)) {
             // due to merging of individual table and
             // contact table, we need to avoid
             // preferred_communication_method forcefully
             $formatValues['contact_type'] = $formatted['contact_type'];
         }
         if ($key == 'id' && isset($field)) {
             $formatted[$key] = $field;
         }
         _civicrm_add_formatted_param($formatValues, $formatted);
         //Handling Custom Data
         if (($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) && array_key_exists($customFieldID, $customFields)) {
             //get the html type.
             $type = $customFields[$customFieldID]['html_type'];
             switch ($type) {
                 case 'CheckBox':
                 case 'AdvMulti-Select':
                 case 'Multi-Select':
                     $mulValues = explode(',', $field);
                     $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true);
                     $formatted[$key] = array();
                     foreach ($mulValues as $v1) {
                         foreach ($customOption as $v2) {
                             if (strtolower($v2['label']) == strtolower(trim($v1)) || strtolower($v2['value']) == strtolower(trim($v1))) {
                                 if ($type == 'CheckBox') {
                                     $formatted[$key][$v2['value']] = 1;
                                 } else {
                                     $formatted[$key][] = $v2['value'];
                                 }
                             }
                         }
                     }
                     break;
                 case 'Select':
                 case 'Radio':
                     $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true);
                     foreach ($customOption as $v2) {
                         if (strtolower($v2['label']) == strtolower(trim($field)) || strtolower($v2['value']) == strtolower(trim($field))) {
                             $formatted[$key] = $v2['value'];
                         }
                     }
                     break;
                 case 'Multi-Select State/Province':
                     $mulValues = explode(',', $field);
                     $stateAbbr = CRM_Core_PseudoConstant::stateProvinceAbbreviation();
                     $stateName = CRM_Core_PseudoConstant::stateProvince();
                     $formatted[$key] = $stateValues = array();
                     foreach ($mulValues as $values) {
                         if ($val = CRM_Utils_Array::key($values, $stateAbbr)) {
                             $formatted[$key][] = $val;
                         } else {
                             if ($val = CRM_Utils_Array::key($values, $stateName)) {
                                 $formatted[$key][] = $val;
                             }
                         }
                     }
                     break;
                 case 'Multi-Select Country':
                     $config =& CRM_Core_Config::singleton();
                     $limitCodes = $config->countryLimit();
                     $mulValues = explode(',', $field);
                     $formatted[$key] = array();
                     CRM_Core_PseudoConstant::populate($countryNames, 'CRM_Core_DAO_Country', true, 'name', 'is_active');
                     CRM_Core_PseudoConstant::populate($countryIsoCodes, 'CRM_Core_DAO_Country', true, 'iso_code');
                     foreach ($mulValues as $values) {
                         if ($val = CRM_Utils_Array::key($values, $countryNames)) {
                             $formatted[$key][] = $val;
                         } else {
                             if ($val = CRM_Utils_Array::key($values, $countryIsoCodes)) {
                                 $formatted[$key][] = $val;
                             } else {
                                 if ($val = CRM_Utils_Array::key($values, $limitCodes)) {
                                     $formatted[$key][] = $val;
                                 }
                             }
                         }
                     }
                     break;
             }
         }
     }
     // check for primary location type, whether it is already present for the contact or not, CRM-4423
     if (CRM_Utils_Array::value('id', $formatted) && isset($formatted['location'])) {
         $primaryLocationTypeId = CRM_Contact_BAO_Contact::getPrimaryLocationType($formatted['id'], true);
         if (isset($primaryLocationTypeId)) {
             foreach ($formatted['location'] as $loc => $details) {
                 if ($primaryLocationTypeId == CRM_Utils_Array::value('location_type_id', $details)) {
                     $formatted['location'][$loc]['is_primary'] = 1;
                     break;
                 } else {
                     $formatted['location'][$loc]['is_primary'] = 0;
                 }
             }
         }
     }
     // parse street address, CRM-5450
     if ($this->_parseStreetAddress) {
         require_once 'CRM/Core/BAO/Address.php';
         if (array_key_exists('address', $formatted) && is_array($formatted['address'])) {
             foreach ($formatted['address'] as $instance => &$address) {
                 $streetAddress = CRM_Utils_Array::value('street_address', $address);
                 if (empty($streetAddress)) {
                     continue;
                 }
                 // parse address field.
                 $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($streetAddress);
                 //street address consider to be parsed properly,
                 //If we get street_name and street_number.
                 if (!CRM_Utils_Array::value('street_name', $parsedFields) || !CRM_Utils_Array::value('street_number', $parsedFields)) {
                     $parsedFields = array_fill_keys(array_keys($parsedFields), '');
                 }
                 // merge parse address w/ main address block.
                 $address = array_merge($address, $parsedFields);
             }
         }
     }
 }
 /**
  * Handle the values in import mode.
  *
  * @param int $onDuplicate
  *   The code for what action to take on duplicates.
  * @param array $values
  *   The array of values belonging to this line.
  *
  * @return bool
  *   the result of this processing
  */
 public function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $session = CRM_Core_Session::singleton();
     $dateType = $session->get('dateTypes');
     $formatted = array('version' => 3);
     $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
     // don't add to recent items, CRM-4399
     $formatted['skipRecentView'] = TRUE;
     foreach ($params as $key => $val) {
         if ($val) {
             if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                 if ($customFields[$customFieldID]['data_type'] == 'Date') {
                     CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                     unset($params[$key]);
                 } elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                     $params[$key] = CRM_Utils_String::strtoboolstr($val);
                 }
             }
             if ($key == 'participant_register_date') {
                 CRM_Utils_Date::convertToDefaultDate($params, $dateType, 'participant_register_date');
                 $formatted['participant_register_date'] = CRM_Utils_Date::processDate($params['participant_register_date']);
             }
         }
     }
     if (!(!empty($params['participant_role_id']) || !empty($params['participant_role']))) {
         if (!empty($params['event_id'])) {
             $params['participant_role_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'default_role_id');
         } else {
             $eventTitle = $params['event_title'];
             $qParams = array();
             $dao = new CRM_Core_DAO();
             $params['participant_role_id'] = $dao->singleValueQuery("SELECT default_role_id FROM civicrm_event WHERE title = '{$eventTitle}' ", $qParams);
         }
     }
     //date-Format part ends
     static $indieFields = NULL;
     if ($indieFields == NULL) {
         $indieFields = CRM_Event_BAO_Participant::import();
     }
     $formatValues = array();
     foreach ($params as $key => $field) {
         if ($field == NULL || $field === '') {
             continue;
         }
         $formatValues[$key] = $field;
     }
     $formatError = _civicrm_api3_deprecated_participant_formatted_param($formatValues, $formatted, TRUE);
     if ($formatError) {
         array_unshift($values, $formatError['error_message']);
         return CRM_Import_Parser::ERROR;
     }
     if (!CRM_Utils_Rule::integer($formatted['event_id'])) {
         array_unshift($values, ts('Invalid value for Event ID'));
         return CRM_Import_Parser::ERROR;
     }
     if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) {
         $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, NULL, 'Participant');
     } else {
         if ($formatValues['participant_id']) {
             $dao = new CRM_Event_BAO_Participant();
             $dao->id = $formatValues['participant_id'];
             $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, $formatValues['participant_id'], 'Participant');
             if ($dao->find(TRUE)) {
                 $ids = array('participant' => $formatValues['participant_id'], 'userId' => $session->get('userID'));
                 $participantValues = array();
                 //@todo calling api functions directly is not supported
                 $newParticipant = _civicrm_api3_deprecated_participant_check_params($formatted, $participantValues, FALSE);
                 if ($newParticipant['error_message']) {
                     array_unshift($values, $newParticipant['error_message']);
                     return CRM_Import_Parser::ERROR;
                 }
                 $newParticipant = CRM_Event_BAO_Participant::create($formatted, $ids);
                 if (!empty($formatted['fee_level'])) {
                     $otherParams = array('fee_label' => $formatted['fee_level'], 'event_id' => $newParticipant->event_id);
                     CRM_Price_BAO_LineItem::syncLineItems($newParticipant->id, 'civicrm_participant', $newParticipant->fee_amount, $otherParams);
                 }
                 $this->_newParticipant[] = $newParticipant->id;
                 return CRM_Import_Parser::VALID;
             } else {
                 array_unshift($values, 'Matching Participant record not found for Participant ID ' . $formatValues['participant_id'] . '. Row was skipped.');
                 return CRM_Import_Parser::ERROR;
             }
         }
     }
     if ($this->_contactIdIndex < 0) {
         //retrieve contact id using contact dedupe rule
         $formatValues['contact_type'] = $this->_contactType;
         $formatValues['version'] = 3;
         $error = _civicrm_api3_deprecated_check_contact_dedupe($formatValues);
         if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) >= 1) {
                 foreach ($matchedIDs as $contactId) {
                     $formatted['contact_id'] = $contactId;
                     $formatted['version'] = 3;
                     $newParticipant = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate);
                 }
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $this->_contactType, 'used' => 'Unsupervised');
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             $disp = '';
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (!empty($params['external_identifier'])) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, 'No matching Contact found for (' . $disp . ')');
             return CRM_Import_Parser::ERROR;
         }
     } else {
         if (!empty($formatValues['external_identifier'])) {
             $checkCid = new CRM_Contact_DAO_Contact();
             $checkCid->external_identifier = $formatValues['external_identifier'];
             $checkCid->find(TRUE);
             if ($checkCid->id != $formatted['contact_id']) {
                 array_unshift($values, 'Mismatch of External ID:' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
                 return CRM_Import_Parser::ERROR;
             }
         }
         $newParticipant = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate);
     }
     if (is_array($newParticipant) && civicrm_error($newParticipant)) {
         if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
             $contactID = CRM_Utils_Array::value('contactID', $newParticipant);
             $participantID = CRM_Utils_Array::value('participantID', $newParticipant);
             $url = CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&id={$participantID}&cid={$contactID}&action=view", TRUE);
             if (is_array($newParticipant['error_message']) && $participantID == $newParticipant['error_message']['params'][0]) {
                 array_unshift($values, $url);
                 return CRM_Import_Parser::DUPLICATE;
             } elseif ($newParticipant['error_message']) {
                 array_unshift($values, $newParticipant['error_message']);
                 return CRM_Import_Parser::ERROR;
             }
             return CRM_Import_Parser::ERROR;
         }
     }
     if (!(is_array($newParticipant) && civicrm_error($newParticipant))) {
         $this->_newParticipants[] = CRM_Utils_Array::value('id', $newParticipant);
     }
     return CRM_Import_Parser::VALID;
 }
Example #5
0
 /**
  * @param $date
  * @param $dateType
  *
  * @return null|string
  */
 public static function formatDate($date, $dateType)
 {
     $formattedDate = NULL;
     if (empty($date)) {
         return $formattedDate;
     }
     // 1. first convert date to default format.
     // 2. append time to default formatted date (might be removed during format)
     // 3. validate date / date time.
     // 4. If date and time then convert to default date time format.
     $dateKey = 'date';
     $dateParams = array($dateKey => $date);
     if (CRM_Utils_Date::convertToDefaultDate($dateParams, $dateType, $dateKey)) {
         $dateVal = $dateParams[$dateKey];
         $ruleName = 'date';
         if ($dateType == 1) {
             $matches = array();
             if (preg_match("/(\\s(([01]\\d)|[2][0-3]):([0-5]\\d))\$/", $date, $matches)) {
                 $ruleName = 'dateTime';
                 if (strpos($date, '-') !== FALSE) {
                     $dateVal .= array_shift($matches);
                 }
             }
         }
         // validate date.
         $valid = CRM_Utils_Rule::$ruleName($dateVal);
         if ($valid) {
             // format date and time to default.
             if ($ruleName == 'dateTime') {
                 $dateVal = CRM_Utils_Date::customFormat(preg_replace("/(:|\\s)?/", "", $dateVal), '%Y%m%d%H%i');
                 // hack to add seconds
                 $dateVal .= '00';
             }
             $formattedDate = $dateVal;
         }
     }
     return $formattedDate;
 }
 /**
  * Format common params data to proper format to store.
  *
  * @param array $params
  *   Contain record values.
  * @param array $formatted
  *   Array of formatted data.
  * @param array $contactFields
  *   Contact DAO fields.
  */
 public function formatCommonData($params, &$formatted, &$contactFields)
 {
     $csType = array(CRM_Utils_Array::value('contact_type', $formatted));
     //CRM-5125
     //add custom fields for contact sub type
     if (!empty($this->_contactSubType)) {
         $csType = $this->_contactSubType;
     }
     if ($relCsType = CRM_Utils_Array::value('contact_sub_type', $formatted)) {
         $csType = $relCsType;
     }
     $customFields = CRM_Core_BAO_CustomField::getFields($formatted['contact_type'], FALSE, FALSE, $csType);
     $addressCustomFields = CRM_Core_BAO_CustomField::getFields('Address');
     $customFields = $customFields + $addressCustomFields;
     //if a Custom Email Greeting, Custom Postal Greeting or Custom Addressee is mapped, and no "Greeting / Addressee Type ID" is provided, then automatically set the type = Customized, CRM-4575
     $elements = array('email_greeting_custom' => 'email_greeting', 'postal_greeting_custom' => 'postal_greeting', 'addressee_custom' => 'addressee');
     foreach ($elements as $k => $v) {
         if (array_key_exists($k, $params) && !array_key_exists($v, $params)) {
             $label = key(CRM_Core_OptionGroup::values($v, TRUE, NULL, NULL, 'AND v.name = "Customized"'));
             $params[$v] = $label;
         }
     }
     //format date first
     $session = CRM_Core_Session::singleton();
     $dateType = $session->get("dateTypes");
     foreach ($params as $key => $val) {
         $customFieldID = CRM_Core_BAO_CustomField::getKeyID($key);
         if ($customFieldID && !array_key_exists($customFieldID, $addressCustomFields)) {
             //we should not update Date to null, CRM-4062
             if ($val && $customFields[$customFieldID]['data_type'] == 'Date') {
                 self::formatCustomDate($params, $formatted, $dateType, $key);
             } elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                 if (empty($val) && !is_numeric($val) && $this->_onDuplicate == CRM_Import_Parser::DUPLICATE_FILL) {
                     //retain earlier value when Import mode is `Fill`
                     unset($params[$key]);
                 } else {
                     $params[$key] = CRM_Utils_String::strtoboolstr($val);
                 }
             }
             if ($key == 'birth_date' && $val) {
                 CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
             } elseif ($key == 'deceased_date' && $val) {
                 CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
             } elseif ($key == 'is_deceased' && $val) {
                 $params[$key] = CRM_Utils_String::strtoboolstr($val);
             } elseif ($key == 'gender') {
                 //CRM-4360
                 $params[$key] = $this->checkGender($val);
             }
         }
     }
     //now format custom data.
     foreach ($params as $key => $field) {
         if (is_array($field)) {
             $isAddressCustomField = FALSE;
             foreach ($field as $value) {
                 $break = FALSE;
                 if (is_array($value)) {
                     foreach ($value as $name => $testForEmpty) {
                         if ($addressCustomFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
                             $isAddressCustomField = TRUE;
                             break;
                         }
                         // check if $value does not contain IM provider or phoneType
                         if (($name !== 'phone_type_id' || $name !== 'provider_id') && ($testForEmpty === '' || $testForEmpty == NULL)) {
                             $break = TRUE;
                             break;
                         }
                     }
                 } else {
                     $break = TRUE;
                 }
                 if (!$break) {
                     require_once 'CRM/Utils/DeprecatedUtils.php';
                     _civicrm_api3_deprecated_add_formatted_param($value, $formatted);
                 }
             }
             if (!$isAddressCustomField) {
                 continue;
             }
         }
         $formatValues = array($key => $field);
         if ($key !== 'preferred_communication_method' && array_key_exists($key, $contactFields)) {
             // due to merging of individual table and
             // contact table, we need to avoid
             // preferred_communication_method forcefully
             $formatValues['contact_type'] = $formatted['contact_type'];
         }
         if ($key == 'id' && isset($field)) {
             $formatted[$key] = $field;
         }
         require_once 'CRM/Utils/DeprecatedUtils.php';
         _civicrm_api3_deprecated_add_formatted_param($formatValues, $formatted);
         //Handling Custom Data
         // note: Address custom fields will be handled separately inside _civicrm_api3_deprecated_add_formatted_param
         if (($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) && array_key_exists($customFieldID, $customFields) && !array_key_exists($customFieldID, $addressCustomFields)) {
             $extends = CRM_Utils_Array::value('extends', $customFields[$customFieldID]);
             $htmlType = CRM_Utils_Array::value('html_type', $customFields[$customFieldID]);
             switch ($htmlType) {
                 case 'Select':
                 case 'Radio':
                 case 'Autocomplete-Select':
                     if ($customFields[$customFieldID]['data_type'] == 'String') {
                         $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
                         foreach ($customOption as $customFldID => $customValue) {
                             $val = CRM_Utils_Array::value('value', $customValue);
                             $label = CRM_Utils_Array::value('label', $customValue);
                             $label = strtolower($label);
                             $value = strtolower(trim($formatted[$key]));
                             if ($value == $label || $value == strtolower($val)) {
                                 $params[$key] = $formatted[$key] = $val;
                             }
                         }
                     }
                     break;
                 case 'CheckBox':
                 case 'AdvMulti-Select':
                 case 'Multi-Select':
                     if (!empty($formatted[$key]) && !empty($params[$key])) {
                         $mulValues = explode(',', $formatted[$key]);
                         $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
                         $formatted[$key] = array();
                         $params[$key] = array();
                         foreach ($mulValues as $v1) {
                             foreach ($customOption as $v2) {
                                 if (strtolower($v2['label']) == strtolower(trim($v1)) || strtolower($v2['value']) == strtolower(trim($v1))) {
                                     if ($htmlType == 'CheckBox') {
                                         $params[$key][$v2['value']] = $formatted[$key][$v2['value']] = 1;
                                     } else {
                                         $params[$key][] = $formatted[$key][] = $v2['value'];
                                     }
                                 }
                             }
                         }
                     }
                     break;
             }
         }
     }
     if (($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) && array_key_exists($customFieldID, $customFields) && !array_key_exists($customFieldID, $addressCustomFields)) {
         // @todo calling api functions directly is not supported
         _civicrm_api3_custom_format_params($params, $formatted, $extends);
     }
     // to check if not update mode and unset the fields with empty value.
     if (!$this->_updateWithId && array_key_exists('custom', $formatted)) {
         foreach ($formatted['custom'] as $customKey => $customvalue) {
             if (empty($formatted['custom'][$customKey][-1]['is_required'])) {
                 $formatted['custom'][$customKey][-1]['is_required'] = $customFields[$customKey]['is_required'];
             }
             $emptyValue = CRM_Utils_Array::value('value', $customvalue[-1]);
             if (!isset($emptyValue)) {
                 unset($formatted['custom'][$customKey]);
             }
         }
     }
     // parse street address, CRM-5450
     if ($this->_parseStreetAddress) {
         if (array_key_exists('address', $formatted) && is_array($formatted['address'])) {
             foreach ($formatted['address'] as $instance => &$address) {
                 $streetAddress = CRM_Utils_Array::value('street_address', $address);
                 if (empty($streetAddress)) {
                     continue;
                 }
                 // parse address field.
                 $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($streetAddress);
                 //street address consider to be parsed properly,
                 //If we get street_name and street_number.
                 if (empty($parsedFields['street_name']) || empty($parsedFields['street_number'])) {
                     $parsedFields = array_fill_keys(array_keys($parsedFields), '');
                 }
                 // merge parse address w/ main address block.
                 $address = array_merge($address, $parsedFields);
             }
         }
     }
 }
Example #7
0
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Member_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     //assign join date equal to start date if join date is not provided
     if (!$params['join_date'] && $params['membership_start_date']) {
         $params['join_date'] = $params['membership_start_date'];
     }
     $session =& CRM_Core_Session::singleton();
     $dateType = $session->get("dateTypes");
     $formatted = array();
     $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
     // don't add to recent items, CRM-4399
     $formatted['skipRecentView'] = true;
     foreach ($params as $key => $val) {
         if ($val) {
             switch ($key) {
                 case 'join_date':
                     if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                         if (!CRM_Utils_Rule::date($params[$key])) {
                             CRM_Import_Parser_Contact::addToErrorMsg('Join Date', $errorMessage);
                         }
                     } else {
                         CRM_Import_Parser_Contact::addToErrorMsg('Join Date', $errorMessage);
                     }
                     break;
                 case 'membership_start_date':
                     if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                         if (!CRM_Utils_Rule::date($params[$key])) {
                             CRM_Import_Parser_Contact::addToErrorMsg('Start Date', $errorMessage);
                         }
                     } else {
                         CRM_Import_Parser_Contact::addToErrorMsg('Start Date', $errorMessage);
                     }
                     break;
                 case 'membership_end_date':
                     if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                         if (!CRM_Utils_Rule::date($params[$key])) {
                             CRM_Import_Parser_Contact::addToErrorMsg('End Date', $errorMessage);
                         }
                     } else {
                         CRM_Import_Parser_Contact::addToErrorMsg('End Date', $errorMessage);
                     }
                     break;
                 case 'is_override':
                     $params[$key] = CRM_Utils_String::strtobool($val);
                     break;
             }
             if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                 if ($customFields[$customFieldID][2] == 'Date') {
                     CRM_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                     unset($params[$key]);
                 } else {
                     if ($customFields[$customFieldID][2] == 'Boolean') {
                         $params[$key] = CRM_Utils_String::strtoboolstr($val);
                     }
                 }
             }
         }
     }
     //date-Format part ends
     static $indieFields = null;
     if ($indieFields == null) {
         require_once 'CRM/Member/DAO/Membership.php';
         $tempIndieFields =& CRM_Member_DAO_Membership::import();
         $indieFields = $tempIndieFields;
     }
     $formatValues = array();
     foreach ($params as $key => $field) {
         if ($field == null || $field === '') {
             continue;
         }
         $formatValues[$key] = $field;
     }
     $formatError = _civicrm_membership_formatted_param($formatValues, $formatted, true);
     if ($formatError) {
         array_unshift($values, $formatError['error_message']);
         return CRM_Member_Import_Parser::ERROR;
     }
     if ($onDuplicate != CRM_Member_Import_Parser::DUPLICATE_UPDATE) {
         $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, null, 'Membership');
     } else {
         //fix for CRM-2219 Update Membership
         // onDuplicate == CRM_Member_Import_Parser::DUPLICATE_UPDATE
         if (CRM_Utils_Array::value('is_override', $formatted) && !CRM_Utils_Array::value('status_id', $formatted)) {
             array_unshift($values, "Required parameter missing: Status");
             return CRM_Member_Import_Parser::ERROR;
         }
         if ($formatValues['membership_id']) {
             require_once 'CRM/Member/BAO/Membership.php';
             $dao = new CRM_Member_BAO_Membership();
             $dao->id = $formatValues['membership_id'];
             $dates = array('join_date', 'start_date', 'end_date');
             foreach ($dates as $v) {
                 if (!$formatted[$v]) {
                     $formatted[$v] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $formatValues['membership_id'], $v);
                 }
             }
             $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, $formatValues['membership_id'], 'Membership');
             if ($dao->find(true)) {
                 $ids = array('membership' => $formatValues['membership_id'], 'userId' => $session->get('userID'));
                 $newMembership =& CRM_Member_BAO_Membership::create($formatted, $ids, true);
                 if (civicrm_error($newMembership)) {
                     array_unshift($values, $newMembership['is_error'] . " for Membership ID " . $formatValues['membership_id'] . ". Row was skipped.");
                     return CRM_Member_Import_Parser::ERROR;
                 } else {
                     $this->_newMemberships[] = $newMembership->id;
                     return CRM_Member_Import_Parser::VALID;
                 }
             } else {
                 array_unshift($values, "Matching Membership record not found for Membership ID " . $formatValues['membership_id'] . ". Row was skipped.");
                 return CRM_Member_Import_Parser::ERROR;
             }
         }
     }
     //Format dates
     $startDate = CRM_Utils_Date::customFormat($formatted['start_date'], '%Y-%m-%d');
     $endDate = CRM_Utils_Date::customFormat($formatted['end_date'], '%Y-%m-%d');
     $joinDate = CRM_Utils_Date::customFormat($formatted['join_date'], '%Y-%m-%d');
     if ($this->_contactIdIndex < 0) {
         //retrieve contact id using contact dedupe rule
         $formatValues['contact_type'] = $this->_contactType;
         $error = civicrm_check_contact_dedupe($formatValues);
         if (civicrm_duplicate($error)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) > 1) {
                 array_unshift($values, "Multiple matching contact records detected for this row. The membership was not imported");
                 return CRM_Member_Import_Parser::ERROR;
             } else {
                 $cid = $matchedIDs[0];
                 $formatted['contact_id'] = $cid;
                 //fix for CRM-1924
                 require_once 'CRM/Member/BAO/MembershipStatus.php';
                 require_once 'CRM/Member/BAO/MembershipType.php';
                 require_once 'CRM/Member/PseudoConstant.php';
                 $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate);
                 self::formattedDates($calcDates, $formatted);
                 //fix for CRM-3570, exclude the statuses those having is_admin = 1
                 //now user can import is_admin if is override is true.
                 $excludeIsAdmin = false;
                 if (!CRM_Utils_Array::value('is_override', $formatted)) {
                     $formatted['exclude_is_admin'] = $excludeIsAdmin = true;
                 }
                 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin);
                 if (!$formatted['status_id']) {
                     $formatted['status_id'] = $calcStatus['id'];
                 } elseif (!CRM_Utils_Array::value('is_override', $formatted)) {
                     if (empty($calcStatus)) {
                         array_unshift($values, "Status in import row (" . $formatValues['status_id'] . ") does not match calculated status based on your configured Membership Status Rules. Record was not imported.");
                         return CRM_Member_Import_Parser::ERROR;
                     } else {
                         if ($formatted['status_id'] != $calcStatus['id']) {
                             //Status Hold" is either NOT mapped or is FALSE
                             array_unshift($values, "Status in import row (" . $formatValues['status_id'] . ") does not match calculated status based on your configured Membership Status Rules (" . $calcStatus['name'] . "). Record was not imported.");
                             return CRM_Member_Import_Parser::ERROR;
                         }
                     }
                 }
                 $newMembership = civicrm_contact_membership_create($formatted);
                 if (civicrm_error($newMembership)) {
                     array_unshift($values, $newMembership['error_message']);
                     return CRM_Member_Import_Parser::ERROR;
                 }
                 $this->_newMemberships[] = $newMembership['id'];
                 return CRM_Member_Import_Parser::VALID;
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $this->_contactType, 'level' => 'Strict');
             require_once 'CRM/Dedupe/BAO/Rule.php';
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (CRM_Utils_Array::value('external_identifier', $params)) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, "No matching Contact found for (" . $disp . ")");
             return CRM_Member_Import_Parser::ERROR;
         }
     } else {
         if ($formatValues['external_identifier']) {
             $checkCid = new CRM_Contact_DAO_Contact();
             $checkCid->external_identifier = $formatValues['external_identifier'];
             $checkCid->find(true);
             if ($checkCid->id != $formatted['contact_id']) {
                 array_unshift($values, "Mismatch of External identifier :" . $formatValues['external_identifier'] . " and Contact Id:" . $formatted['contact_id']);
                 return CRM_Member_Import_Parser::ERROR;
             }
         }
         //to calculate dates
         require_once 'CRM/Member/BAO/MembershipType.php';
         $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate);
         self::formattedDates($calcDates, $formatted);
         //end of date calculation part
         //fix for CRM-3570, exclude the statuses those having is_admin = 1
         //now user can import is_admin if is override is true.
         $excludeIsAdmin = false;
         if (!CRM_Utils_Array::value('is_override', $formatted)) {
             $formatted['exclude_is_admin'] = $excludeIsAdmin = true;
         }
         require_once 'CRM/Member/BAO/MembershipStatus.php';
         $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin);
         if (!$formatted['status_id']) {
             $formatted['status_id'] = $calcStatus['id'];
         } else {
             if (!CRM_Utils_Array::value('is_override', $formatted)) {
                 if (empty($calcStatus)) {
                     array_unshift($values, "Status in import row (" . $formatValues['status_id'] . ") does not match calculated status based on your configured Membership Status Rules. Record was not imported.");
                     return CRM_Member_Import_Parser::ERROR;
                 } else {
                     if ($formatted['status_id'] != $calcStatus['id']) {
                         //Status Hold" is either NOT mapped or is FALSE
                         array_unshift($values, "Status in import row (" . $formatValues['status_id'] . ") does not match calculated status based on your configured Membership Status Rules (" . $calcStatus['name'] . "). Record was not imported.");
                         return CRM_Member_Import_Parser::ERROR;
                     }
                 }
             }
         }
         $newMembership = civicrm_contact_membership_create($formatted);
         if (civicrm_error($newMembership)) {
             array_unshift($values, $newMembership['error_message']);
             return CRM_Member_Import_Parser::ERROR;
         }
         $this->_newMemberships[] = $newMembership['id'];
         return CRM_Member_Import_Parser::VALID;
     }
 }
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Event_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $session = CRM_Core_Session::singleton();
     $dateType = $session->get('dateTypes');
     $formatted = array();
     $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
     // don't add to recent items, CRM-4399
     $formatted['skipRecentView'] = true;
     foreach ($params as $key => $val) {
         if ($val) {
             if ($key == 'participant_register_date') {
                 if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                     if (!CRM_Utils_Rule::date($params[$key])) {
                         CRM_Import_Parser_Contact::addToErrorMsg('Register Date', $errorMessage);
                     }
                 } else {
                     CRM_Import_Parser_Contact::addToErrorMsg('Register Date', $errorMessage);
                 }
             }
             if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                 if ($customFields[$customFieldID]['data_type'] == 'Date') {
                     CRM_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                     unset($params[$key]);
                 } else {
                     if ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                         $params[$key] = CRM_Utils_String::strtoboolstr($val);
                     }
                 }
             }
         }
     }
     if (!($params['participant_role_id'] || $params['participant_role'])) {
         if ($params['event_id']) {
             $params['participant_role_id'] = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Event", $params['event_id'], 'default_role_id');
         } else {
             $eventTitle = $params['event_title'];
             $qParams = array();
             $dao = new CRM_Core_DAO();
             $params['participant_role_id'] = $dao->singleValueQuery("SELECT default_role_id FROM civicrm_event WHERE title = '{$eventTitle}' ", $qParams);
         }
     }
     //date-Format part ends
     static $indieFields = null;
     if ($indieFields == null) {
         require_once 'CRM/Event/BAO/Participant.php';
         $indieFields =& CRM_Event_BAO_Participant::import();
     }
     $formatValues = array();
     foreach ($params as $key => $field) {
         if ($field == null || $field === '') {
             continue;
         }
         $formatValues[$key] = $field;
     }
     $formatError = _civicrm_participant_formatted_param($formatValues, $formatted, true);
     require_once "api/v2/Participant.php";
     if ($formatError) {
         array_unshift($values, $formatError['error_message']);
         return CRM_Event_Import_Parser::ERROR;
     }
     if (!CRM_Utils_Rule::integer($formatted['event_id'])) {
         array_unshift($values, ts('Invalid value for Event ID'));
         return CRM_Event_Import_Parser::ERROR;
     }
     if ($onDuplicate != CRM_Event_Import_Parser::DUPLICATE_UPDATE) {
         $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, null, 'Participant');
     } else {
         if ($formatValues['participant_id']) {
             require_once 'CRM/Event/BAO/Participant.php';
             $dao = new CRM_Event_BAO_Participant();
             $dao->id = $formatValues['participant_id'];
             $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, $formatValues['participant_id'], 'Participant');
             if ($dao->find(true)) {
                 $ids = array('participant' => $formatValues['participant_id'], 'userId' => $session->get('userID'));
                 $newParticipant = civicrm_participant_check_params($formatted, false);
                 if ($newParticipant['error_message']) {
                     array_unshift($values, $newParticipant['error_message']);
                     return CRM_Event_Import_Parser::ERROR;
                 }
                 $newParticipant =& CRM_Event_BAO_Participant::create($formatted, $ids);
                 $this->_newParticipant[] = $newParticipant->id;
                 return CRM_Event_Import_Parser::VALID;
             } else {
                 array_unshift($values, "Matching Participant record not found for Participant ID " . $formatValues['participant_id'] . ". Row was skipped.");
                 return CRM_Event_Import_Parser::ERROR;
             }
         }
     }
     if ($this->_contactIdIndex < 0) {
         //retrieve contact id using contact dedupe rule
         $formatValues['contact_type'] = $this->_contactType;
         $error = civicrm_check_contact_dedupe($formatValues);
         if (civicrm_duplicate($error)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) >= 1) {
                 foreach ($matchedIDs as $contactId) {
                     $formatted['contact_id'] = $contactId;
                     $newParticipant = civicrm_create_participant_formatted($formatted, $onDuplicate);
                 }
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $this->_contactType, 'level' => 'Strict');
             require_once 'CRM/Dedupe/BAO/Rule.php';
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (CRM_Utils_Array::value('external_identifier', $params)) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, "No matching Contact found for (" . $disp . ")");
             return CRM_Event_Import_Parser::ERROR;
         }
     } else {
         if ($formatValues['external_identifier']) {
             $checkCid = new CRM_Contact_DAO_Contact();
             $checkCid->external_identifier = $formatValues['external_identifier'];
             $checkCid->find(true);
             if ($checkCid->id != $formatted['contact_id']) {
                 array_unshift($values, "Mismatch of External identifier :" . $formatValues['external_identifier'] . " and Contact Id:" . $formatted['contact_id']);
                 return CRM_Event_Import_Parser::ERROR;
             }
         }
         $newParticipant = civicrm_create_participant_formatted($formatted, $onDuplicate);
     }
     if (is_array($newParticipant) && civicrm_error($newParticipant)) {
         if ($onDuplicate == CRM_Event_Import_Parser::DUPLICATE_SKIP) {
             $contactID = CRM_Utils_Array::value('contactID', $newParticipant['error_data']);
             $participantID = CRM_Utils_Array::value('participantID', $newParticipant['error_data']);
             $url = CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&id={$participantID}&cid={$contactID}&action=view", true);
             if (is_array($newParticipant['error_message']) && $participantID == $newParticipant['error_message']['params'][0]) {
                 array_unshift($values, $url);
                 return CRM_Event_Import_Parser::DUPLICATE;
             } else {
                 if ($newParticipant['error_message']) {
                     array_unshift($values, $newParticipant['error_message']);
                     return CRM_Event_Import_Parser::ERROR;
                 }
             }
             return CRM_Event_Import_Parser::ERROR;
         }
     }
     if (!(is_array($newParticipant) && civicrm_error($newParticipant))) {
         $this->_newParticipants[] = $newParticipant['id'];
     }
     return CRM_Event_Import_Parser::VALID;
 }
Example #9
0
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Activity_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $activityName = array_search('activity_name', $this->_mapperKeys);
     if ($activityName) {
         $params = array_merge($params, array('activity_name' => $values[$activityName]));
     }
     //for date-Formats
     $session =& CRM_Core_Session::singleton();
     $dateType = $session->get("dateTypes");
     $params['source_contact_id'] = $session->get('userID');
     $formatted = array();
     $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
     foreach ($params as $key => $val) {
         if ($key == 'activity_date_time') {
             if ($val) {
                 if ($dateType == 1) {
                     $params[$key] = CRM_Utils_Date::customFormat($val, '%Y%m%d%H%i');
                     //hack to add seconds
                     $params[$key] = $params[$key] . '00';
                 } else {
                     CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
                 }
             }
         } elseif ($key == 'duration') {
             $params['duration_minutes'] = $params['duration'];
             unset($params['duration']);
         }
         if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
             if ($customFields[$customFieldID]['data_type'] == 'Date') {
                 CRM_Import_Parser_Contact::formatCustomDate($params, $params, $dateType, $key);
             } else {
                 if ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                     $params[$key] = CRM_Utils_String::strtoboolstr($val);
                 }
             }
         }
     }
     //date-Format part ends
     $formatError = _civicrm_activity_formatted_param($params, $params, true);
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, CRM_Core_DAO::$_nullObject, null, 'Activity');
     if ($this->_contactIdIndex < 0) {
         //retrieve contact id using contact dedupe rule.
         //since we are support only individual's activity import.
         $params['contact_type'] = 'Individual';
         $error = civicrm_check_contact_dedupe($params);
         if (civicrm_duplicate($error)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) > 1) {
                 array_unshift($values, "Multiple matching contact records detected for this row. The activity was not imported");
                 return CRM_Activity_Import_Parser::ERROR;
             } else {
                 $cid = $matchedIDs[0];
                 $params['target_contact_id'] = $cid;
                 $newActivity = civicrm_activity_create($params);
                 if (CRM_Utils_Array::value('is_error', $newActivity)) {
                     array_unshift($values, $newActivity['error_message']);
                     return CRM_Activity_Import_Parser::ERROR;
                 }
                 $this->_newActivity[] = $newActivity['id'];
                 return CRM_Activity_Import_Parser::VALID;
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => 'Individual', 'level' => 'Strict');
             require_once 'CRM/Dedupe/BAO/Rule.php';
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (CRM_Utils_Array::value('external_identifier', $params)) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, "No matching Contact found for (" . $disp . ")");
             return CRM_Activity_Import_Parser::ERROR;
         }
     } else {
         if (CRM_Utils_Array::value('external_identifier', $params)) {
             $targetContactId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['external_identifier'], 'id', 'external_identifier');
             if (CRM_Utils_Array::value('target_contact_id', $params) && $params['target_contact_id'] != $targetContactId) {
                 array_unshift($values, "Mismatch of External identifier :" . $params['external_identifier'] . " and Contact Id:" . $params['target_contact_id']);
                 return CRM_Activity_Import_Parser::ERROR;
             } else {
                 if ($targetContactId) {
                     $params['target_contact_id'] = $targetContactId;
                 } else {
                     array_unshift($values, "No Matching Contact for External identifier :" . $params['external_identifier']);
                     return CRM_Activity_Import_Parser::ERROR;
                 }
             }
         }
         $newActivity = civicrm_activity_create($params);
         if (CRM_Utils_Array::value('is_error', $newActivity)) {
             array_unshift($values, $newActivity['error_message']);
             return CRM_Activity_Import_Parser::ERROR;
         }
         $this->_newActivity[] = $newActivity['id'];
         return CRM_Activity_Import_Parser::VALID;
     }
 }
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_Contribute_Import_Parser::VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $formatted = array('version' => 3);
     // don't add to recent items, CRM-4399
     $formatted['skipRecentView'] = TRUE;
     //for date-Formats
     $session = CRM_Core_Session::singleton();
     $dateType = $session->get("dateTypes");
     $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
     foreach ($params as $key => $val) {
         if ($val) {
             switch ($key) {
                 case 'receive_date':
                     CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
                     break;
                 case 'cancel_date':
                     CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
                     break;
                 case 'receipt_date':
                     CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
                     break;
                 case 'thankyou_date':
                     CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
                     break;
                 case 'pledge_payment':
                     $params[$key] = CRM_Utils_String::strtobool($val);
                     break;
             }
             if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                 if ($customFields[$customFieldID]['data_type'] == 'Date') {
                     CRM_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
                     unset($params[$key]);
                 } elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
                     $params[$key] = CRM_Utils_String::strtoboolstr($val);
                 }
             }
         }
     }
     //date-Format part ends
     static $indieFields = NULL;
     if ($indieFields == NULL) {
         $tempIndieFields = CRM_Contribute_DAO_Contribution::import();
         $indieFields = $tempIndieFields;
     }
     $paramValues = array();
     foreach ($params as $key => $field) {
         if ($field == NULL || $field === '') {
             continue;
         }
         $paramValues[$key] = $field;
     }
     //import contribution record according to select contact type
     if ($onDuplicate == CRM_Contribute_Import_Parser::DUPLICATE_SKIP && (CRM_Utils_Array::value('contribution_contact_id', $paramValues) || CRM_Utils_Array::value('external_identifier', $paramValues))) {
         $paramValues['contact_type'] = $this->_contactType;
     } elseif ($onDuplicate == CRM_Contribute_Import_Parser::DUPLICATE_UPDATE && ($paramValues['contribution_id'] || $values['trxn_id'] || $paramValues['invoice_id'])) {
         $paramValues['contact_type'] = $this->_contactType;
     } elseif (!empty($params['soft_credit'])) {
         $paramValues['contact_type'] = $this->_contactType;
     } elseif (CRM_Utils_Array::value('pledge_payment', $paramValues)) {
         $paramValues['contact_type'] = $this->_contactType;
     }
     //need to pass $onDuplicate to check import mode.
     if (CRM_Utils_Array::value('pledge_payment', $paramValues)) {
         $paramValues['onDuplicate'] = $onDuplicate;
     }
     require_once 'api/v3/DeprecatedUtils.php';
     $formatError = _civicrm_api3_deprecated_formatted_param($paramValues, $formatted, TRUE);
     if ($formatError) {
         array_unshift($values, $formatError['error_message']);
         if (CRM_Utils_Array::value('error_data', $formatError) == 'soft_credit') {
             return CRM_Contribute_Import_Parser::SOFT_CREDIT_ERROR;
         } elseif (CRM_Utils_Array::value('error_data', $formatError) == 'pledge_payment') {
             return CRM_Contribute_Import_Parser::PLEDGE_PAYMENT_ERROR;
         }
         return CRM_Contribute_Import_Parser::ERROR;
     }
     if ($onDuplicate != CRM_Contribute_Import_Parser::DUPLICATE_UPDATE) {
         $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, NULL, 'Contribution');
     } else {
         //fix for CRM-2219 - Update Contribution
         // onDuplicate == CRM_Contribute_Import_Parser::DUPLICATE_UPDATE
         if (CRM_Utils_Array::value('invoice_id', $paramValues) || CRM_Utils_Array::value('trxn_id', $paramValues) || $paramValues['contribution_id']) {
             $dupeIds = array('id' => CRM_Utils_Array::value('contribution_id', $paramValues), 'trxn_id' => CRM_Utils_Array::value('trxn_id', $paramValues), 'invoice_id' => CRM_Utils_Array::value('invoice_id', $paramValues));
             $ids['contribution'] = CRM_Contribute_BAO_Contribution::checkDuplicateIds($dupeIds);
             if ($ids['contribution']) {
                 $formatted['id'] = $ids['contribution'];
                 $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, $formatted['id'], 'Contribution');
                 //process note
                 if (CRM_Utils_Array::value('note', $paramValues)) {
                     $noteID = array();
                     $contactID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'contact_id');
                     $daoNote = new CRM_Core_BAO_Note();
                     $daoNote->entity_table = 'civicrm_contribution';
                     $daoNote->entity_id = $ids['contribution'];
                     if ($daoNote->find(TRUE)) {
                         $noteID['id'] = $daoNote->id;
                     }
                     $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $paramValues['note'], 'entity_id' => $ids['contribution'], 'contact_id' => $contactID);
                     CRM_Core_BAO_Note::add($noteParams, $noteID);
                     unset($formatted['note']);
                 }
                 //need to check existing soft credit contribution, CRM-3968
                 if (CRM_Utils_Array::value('soft_credit_to', $formatted)) {
                     $dupeSoftCredit = array('contact_id' => $formatted['soft_credit_to'], 'contribution_id' => $ids['contribution']);
                     $existingSoftCredit = CRM_Contribute_BAO_Contribution::getSoftContribution($dupeSoftCredit);
                     if (CRM_Utils_Array::value('soft_credit_id', $existingSoftCredit)) {
                         $formatted['softID'] = $existingSoftCredit['soft_credit_id'];
                     }
                 }
                 $newContribution = CRM_Contribute_BAO_Contribution::create($formatted, $ids);
                 CRM_Price_BAO_LineItem::syncLineItems($ids['contribution'], 'civicrm_contribution', CRM_Utils_Array::value('total_amount', $formatted));
                 $this->_newContributions[] = $newContribution->id;
                 //return soft valid since we need to show how soft credits were added
                 if (CRM_Utils_Array::value('soft_credit_to', $formatted)) {
                     return CRM_Contribute_Import_Parser::SOFT_CREDIT;
                 }
                 // process pledge payment assoc w/ the contribution
                 return self::processPledgePayments($formatted);
                 return CRM_Contribute_Import_Parser::VALID;
             } else {
                 $labels = array('id' => 'Contribution ID', 'trxn_id' => 'Transaction ID', 'invoice_id' => 'Invoice ID');
                 foreach ($dupeIds as $k => $v) {
                     if ($v) {
                         $errorMsg[] = "{$labels[$k]} {$v}";
                     }
                 }
                 $errorMsg = implode(' AND ', $errorMsg);
                 array_unshift($values, "Matching Contribution record not found for " . $errorMsg . ". Row was skipped.");
                 return CRM_Contribute_Import_Parser::ERROR;
             }
         }
     }
     if ($this->_contactIdIndex < 0) {
         // set the contact type if its not set
         if (!isset($paramValues['contact_type'])) {
             $paramValues['contact_type'] = $this->_contactType;
         }
         $paramValues['version'] = 3;
         //retrieve contact id using contact dedupe rule
         require_once 'api/v3/DeprecatedUtils.php';
         $error = _civicrm_api3_deprecated_check_contact_dedupe($paramValues);
         if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
             $matchedIDs = explode(',', $error['error_message']['params'][0]);
             if (count($matchedIDs) > 1) {
                 array_unshift($values, "Multiple matching contact records detected for this row. The contribution was not imported");
                 return CRM_Contribute_Import_Parser::ERROR;
             } else {
                 $cid = $matchedIDs[0];
                 $formatted['contact_id'] = $cid;
                 $newContribution = civicrm_api('contribution', 'create', $formatted);
                 if (civicrm_error($newContribution)) {
                     if (is_array($newContribution['error_message'])) {
                         array_unshift($values, $newContribution['error_message']['message']);
                         if ($newContribution['error_message']['params'][0]) {
                             return CRM_Contribute_Import_Parser::DUPLICATE;
                         }
                     } else {
                         array_unshift($values, $newContribution['error_message']);
                         return CRM_Contribute_Import_Parser::ERROR;
                     }
                 }
                 $this->_newContributions[] = $newContribution['id'];
                 $formatted['contribution_id'] = $newContribution['id'];
                 //return soft valid since we need to show how soft credits were added
                 if (CRM_Utils_Array::value('soft_credit_to', $formatted)) {
                     return CRM_Contribute_Import_Parser::SOFT_CREDIT;
                 }
                 // process pledge payment assoc w/ the contribution
                 return self::processPledgePayments($formatted);
                 return CRM_Contribute_Import_Parser::VALID;
             }
         } else {
             // Using new Dedupe rule.
             $ruleParams = array('contact_type' => $this->_contactType, 'level' => 'Strict');
             $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             if (CRM_Utils_Array::value('external_identifier', $params)) {
                 if ($disp) {
                     $disp .= "AND {$params['external_identifier']}";
                 } else {
                     $disp = $params['external_identifier'];
                 }
             }
             array_unshift($values, "No matching Contact found for (" . $disp . ")");
             return CRM_Contribute_Import_Parser::ERROR;
         }
     } else {
         if (CRM_Utils_Array::value('external_identifier', $paramValues)) {
             $checkCid = new CRM_Contact_DAO_Contact();
             $checkCid->external_identifier = $paramValues['external_identifier'];
             $checkCid->find(TRUE);
             if ($checkCid->id != $formatted['contact_id']) {
                 array_unshift($values, "Mismatch of External identifier :" . $paramValues['external_identifier'] . " and Contact Id:" . $formatted['contact_id']);
                 return CRM_Contribute_Import_Parser::ERROR;
             }
         }
         $newContribution = civicrm_api('contribution', 'create', $formatted);
         if (civicrm_error($newContribution)) {
             if (is_array($newContribution['error_message'])) {
                 array_unshift($values, $newContribution['error_message']['message']);
                 if ($newContribution['error_message']['params'][0]) {
                     return CRM_Contribute_Import_Parser::DUPLICATE;
                 }
             } else {
                 array_unshift($values, $newContribution['error_message']);
                 return CRM_Contribute_Import_Parser::ERROR;
             }
         }
         $this->_newContributions[] = $newContribution['id'];
         $formatted['contribution_id'] = $newContribution['id'];
         //return soft valid since we need to show how soft credits were added
         if (CRM_Utils_Array::value('soft_credit_to', $formatted)) {
             return CRM_Contribute_Import_Parser::SOFT_CREDIT;
         }
         // process pledge payment assoc w/ the contribution
         return self::processPledgePayments($formatted);
         return CRM_Contribute_Import_Parser::VALID;
     }
 }
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_CONTRIBUTE_IMPORT_PARSER_VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     //for date-Formats
     $session =& CRM_Core_Session::singleton();
     $dateType = $session->get("dateTypes");
     foreach ($params as $key => $val) {
         if ($val) {
             switch ($key) {
                 case 'receive_date':
                     CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
                     break;
                 case 'cancel_date':
                     CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
                     break;
                 case 'receipt_date':
                     CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
                     break;
                 case 'thankyou_date':
                     CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
                     break;
             }
         }
     }
     //date-Format part ends
     $formatted = array();
     if ($GLOBALS['_CRM_CONTRIBUTE_IMPORT_PARSER_CONTRIBUTION']['indieFields'] == null) {
         require_once 'CRM/Contribute/DAO/Contribution.php';
         $tempIndieFields =& CRM_Contribute_DAO_Contribution::import();
         $GLOBALS['_CRM_CONTRIBUTE_IMPORT_PARSER_CONTRIBUTION']['indieFields'] = $tempIndieFields;
     }
     foreach ($params as $key => $field) {
         if ($field == null || $field === '') {
             continue;
         }
         $value = array($key => $field);
         _crm_add_formatted_contrib_param($value, $formatted);
     }
     if ($this->_contactIdIndex < 0) {
         if ($GLOBALS['_CRM_CONTRIBUTE_IMPORT_PARSER_CONTRIBUTION']['cIndieFields'] == null) {
             require_once 'CRM/Contact/BAO/Contact.php';
             $cTempIndieFields = CRM_Contact_BAO_Contact::importableFields('Individual', null);
             $GLOBALS['_CRM_CONTRIBUTE_IMPORT_PARSER_CONTRIBUTION']['cIndieFields'] = $cTempIndieFields;
         }
         foreach ($params as $key => $field) {
             if ($field == null || $field === '') {
                 continue;
             }
             if (is_array($field)) {
                 foreach ($field as $value) {
                     $break = false;
                     if (is_array($value)) {
                         foreach ($value as $name => $testForEmpty) {
                             if ($name !== 'phone_type' && ($testForEmpty === '' || $testForEmpty == null)) {
                                 $break = true;
                                 break;
                             }
                         }
                     } else {
                         $break = true;
                     }
                     if (!$break) {
                         _crm_add_formatted_param($value, $contactFormatted);
                     }
                 }
                 continue;
             }
             $value = array($key => $field);
             if (array_key_exists($key, $GLOBALS['_CRM_CONTRIBUTE_IMPORT_PARSER_CONTRIBUTION']['cIndieFields'])) {
                 $value['contact_type'] = 'Individual';
             }
             _crm_add_formatted_param($value, $contactFormatted);
         }
         $contactFormatted['contact_type'] = 'Individual';
         $error = _crm_duplicate_formatted_contact($contactFormatted);
         $matchedIDs = explode(',', $error->_errors[0]['params'][0]);
         if (CRM_Contribute_Import_Parser_Contribution::isDuplicate($error)) {
             if (count($matchedIDs) > 1) {
                 array_unshift($values, "Multiple matching contact records detected for this row. The contribution was not imported");
                 return CRM_CONTRIBUTE_IMPORT_PARSER_ERROR;
             } else {
                 $cid = $matchedIDs[0];
                 $formatted['contact_id'] = $cid;
                 $newContribution = crm_create_contribution_formatted($formatted, $onDuplicate);
                 if (is_a($newContribution, CRM_Core_Error)) {
                     array_unshift($values, $newContribution->_errors[0]['message']);
                     return CRM_CONTRIBUTE_IMPORT_PARSER_ERROR;
                 }
                 $this->_newContributions[] = $newContribution->id;
                 return CRM_CONTRIBUTE_IMPORT_PARSER_VALID;
             }
         } else {
             require_once 'CRM/Core/DAO/DupeMatch.php';
             $dao =& new CRM_Core_DAO_DupeMatch();
             $dao->find(true);
             $fieldsArray = explode('AND', $dao->rule);
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             array_unshift($values, "No matching Contact found for (" . $disp . ")");
             return CRM_CONTRIBUTE_IMPORT_PARSER_ERROR;
         }
     } else {
         $newContribution = crm_create_contribution_formatted($formatted, $onDuplicate);
         if (is_a($newContribution, CRM_Core_Error)) {
             array_unshift($values, $newContribution->_errors[0]['message']);
             return CRM_CONTRIBUTE_IMPORT_PARSER_ERROR;
         }
         $this->_newContributions[] = $newContribution->id;
         return CRM_CONTRIBUTE_IMPORT_PARSER_VALID;
     }
 }
Example #12
0
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     //$this->_updateWithId = false;
     $response = $this->summary($values);
     if ($response != CRM_IMPORT_PARSER_VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     $formatted = array('contact_type' => $this->_contactType);
     //for date-Formats
     $session =& CRM_Core_Session::singleton();
     $dateType = $session->get("dateType");
     $customFields = CRM_Core_BAO_CustomField::getFields($params['contact_type']);
     foreach ($params as $key => $val) {
         if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
             if ($customFields[$customFieldID][2] == 'Date') {
                 CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
             }
         }
         if ($key == 'birth_date') {
             if ($val) {
                 CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
             }
         }
     }
     //date-Format part ends
     if ($GLOBALS['_CRM_IMPORT_PARSER_CONTACT']['indieFields'] == null) {
         require_once str_replace('_', DIRECTORY_SEPARATOR, "CRM_Contact_DAO_" . $this->_contactType) . ".php";
         eval('$tempIndieFields =& CRM_Contact_DAO_' . $this->_contactType . '::import();');
         //modified for PHP4 issue
         $GLOBALS['_CRM_IMPORT_PARSER_CONTACT']['indieFields'] = $tempIndieFields;
     }
     foreach ($params as $key => $field) {
         if ($field == null || $field === '') {
             continue;
         }
         if (is_array($field)) {
             foreach ($field as $value) {
                 $break = false;
                 if (is_array($value)) {
                     foreach ($value as $name => $testForEmpty) {
                         if ($name !== 'phone_type' && ($testForEmpty === '' || $testForEmpty == null)) {
                             $break = true;
                             break;
                         }
                     }
                 } else {
                     $break = true;
                 }
                 if (!$break) {
                     _crm_add_formatted_param($value, $formatted);
                 }
             }
             continue;
         }
         $value = array($key => $field);
         if (array_key_exists($key, $GLOBALS['_CRM_IMPORT_PARSER_CONTACT']['indieFields'])) {
             $value['contact_type'] = $this->_contactType;
         }
         _crm_add_formatted_param($value, $formatted);
     }
     /*if (in_array('id',$this->_mapperKeys)) {
           $this->_updateWithId = true;
       }*/
     $relationship = false;
     // Support Match and Update Via Contact ID
     if ($this->_updateWithId) {
         $error = _crm_duplicate_formatted_contact($formatted);
         if (CRM_Import_Parser_Contact::isDuplicate($error)) {
             $matchedIDs = explode(',', $error->_errors[0]['params'][0]);
             if (count($matchedIDs) >= 1) {
                 $updateflag = true;
                 foreach ($matchedIDs as $contactId) {
                     if ($params['id'] == $contactId) {
                         $paramsValues = array('contact_id' => $contactId);
                         $contactExits = crm_get_contact($paramsValues);
                         if ($formatted['contact_type'] == $contactExits->contact_type) {
                             $newContact = crm_update_contact_formatted($contactId, $formatted, true);
                             $updateflag = false;
                             $this->_retCode = CRM_IMPORT_PARSER_VALID;
                         } else {
                             $message = "Mismatched contact Types :";
                             array_unshift($values, $message);
                             $updateflag = false;
                             $this->_retCode = CRM_IMPORT_PARSER_NO_MATCH;
                         }
                     }
                 }
                 if ($updateflag) {
                     $message = "Mismatched contact IDs OR Mismatched contact Types :";
                     array_unshift($values, $message);
                     $this->_retCode = CRM_IMPORT_PARSER_NO_MATCH;
                 }
             }
         } else {
             $paramsValues = array('contact_id' => $params['id']);
             $contact = crm_get_contact($paramsValues);
             if (is_a($contact, CRM_Contact_BAO_Contact)) {
                 if ($formatted['contact_type'] == $contact->contact_type) {
                     $newContact = crm_update_contact_formatted($contact->id, $formatted, true);
                     $this->_retCode = CRM_IMPORT_PARSER_VALID;
                 } else {
                     $message = "Mismatched contact Types :";
                     array_unshift($values, $message);
                     $this->_retCode = CRM_IMPORT_PARSER_NO_MATCH;
                 }
             } else {
                 $message = "No contact found for this contact ID:" . $params['id'];
                 array_unshift($values, $message);
                 $this->_retCode = CRM_IMPORT_PARSER_NO_MATCH;
             }
         }
         if (is_a($newContact, CRM_Contact_BAO_Contact)) {
             $relationship = true;
         } else {
             if (is_a($error, CRM_Core_Error)) {
                 $newContact = $error;
                 $relationship = true;
             }
         }
         if ($newContact && !is_a($newContact, CRM_Core_Error)) {
             $this->_newContacts[] = $newContact->id;
         }
     } else {
         $newContact = crm_create_contact_formatted($formatted, $onDuplicate);
         $relationship = true;
     }
     if ($relationship) {
         if (CRM_Import_Parser_Contact::isDuplicate($newContact)) {
             foreach ($newContact->_errors[0]['params'] as $cid) {
                 $primaryContactId = $cid;
             }
         } else {
             $primaryContactId = $newContact->id;
         }
         if (CRM_Import_Parser_Contact::isDuplicate($newContact) || is_a($newContact, CRM_Contact_BAO_Contact)) {
             //relationship contact insert
             foreach ($params as $key => $field) {
                 list($id, $first, $second) = explode('_', $key);
                 if (!($first == 'a' && $second == 'b') && !($first == 'b' && $second == 'a')) {
                     continue;
                 }
                 $relationType = new CRM_Contact_DAO_RelationshipType();
                 $relationType->id = $id;
                 $relationType->find(true);
                 $name_a_b = $relationType->name_a_b;
                 if ($params[$key]['contact_type']) {
                     $formatting = array('contact_type' => $params[$key]['contact_type']);
                 } else {
                     $fld = array_keys($params[$key]);
                     foreach (CRM_Core_SelectValues::contactType() as $cType => $val) {
                         if ($cType) {
                             $contactFields =& CRM_Contact_BAO_Contact::importableFields($cType);
                             if (array_key_exists($fld[0], $contactFields)) {
                                 $formatting['contact_type'] = $cType;
                                 $params[$key]['contact_type'] = $cType;
                                 $field['contact_type'] = $cType;
                                 break;
                             }
                         }
                     }
                 }
                 $contactFields = null;
                 if ($contactFields == null) {
                     require_once str_replace('_', DIRECTORY_SEPARATOR, "CRM_Contact_DAO_" . $params[$key]['contact_type']) . ".php";
                     eval('$contactFields =& CRM_Contact_DAO_' . $params[$key]['contact_type'] . '::import();');
                 }
                 foreach ($field as $k => $v) {
                     if ($v == null || $v === '') {
                         continue;
                     }
                     if (is_array($v)) {
                         foreach ($v as $value) {
                             $break = false;
                             foreach ($value as $testForEmpty) {
                                 if ($testForEmpty === '' || $testForEmpty == null) {
                                     $break = true;
                                     break;
                                 }
                             }
                             if (!$break) {
                                 _crm_add_formatted_param($value, $formatting);
                             }
                         }
                         continue;
                     }
                     $value = array($k => $v);
                     if (array_key_exists($k, $contactFields)) {
                         $value['contact_type'] = $params[$key]['contact_type'];
                     }
                     _crm_add_formatted_param($value, $formatting);
                 }
                 $relatedNewContact = crm_create_contact_formatted($formatting, $onDuplicate);
                 if (CRM_Import_Parser_Contact::isDuplicate($relatedNewContact)) {
                     foreach ($relatedNewContact->_errors[0]['params'] as $cid) {
                         $relContactId = $cid;
                     }
                 } else {
                     $relContactId = $relatedNewContact->id;
                     $this->_newRelatedContacts[] = $relContactId;
                 }
                 if (CRM_Import_Parser_Contact::isDuplicate($relatedNewContact) || is_a($relatedNewContact, CRM_Contact_BAO_Contact)) {
                     //store the related contact id for groups
                     //$this->_newRelatedContacts[] = $relContactId;
                     // now create the relationship record
                     $relationParams = array();
                     $relationParams = array('relationship_type_id' => $key, 'contact_check' => array($relContactId => 1));
                     $relationIds = array('contact' => $primaryContactId);
                     CRM_Contact_BAO_Relationship::create($relationParams, $relationIds);
                     //check if the two contacts are related and of type individual
                     if ($params[$key]['contact_type'] == 'Individual' && $this->_contactType == 'Individual') {
                         if ($name_a_b == 'Spouse of' || $name_a_b == 'Child of' || $name_a_b == 'Sibling of') {
                             $householdName = "The " . $formatting['last_name'] . " household";
                             $householdFormatting = array('contact_type' => 'Household', 'household_name' => $householdName);
                             $householdContact = crm_create_contact_formatted($householdFormatting, $onDuplicate);
                             if (CRM_Import_Parser_Contact::isDuplicate($householdContact)) {
                                 foreach ($householdContact->_errors[0]['params'] as $cid) {
                                     $householdId = $cid;
                                 }
                             } else {
                                 $householdId = $householdContact->id;
                                 $this->_newRelatedContacts[] = $householdId;
                             }
                             //Household contact is created
                             //for two related individual contacts waiting confirmation whether
                             //to add it in a group
                             //$this->_newRelatedContacts[] = $householdId;
                             $relationParams = array();
                             // adding household relationship
                             $relType = '7_' . $second . '_' . $first;
                             $relationParams = array('relationship_type_id' => $relType, 'contact_check' => array($relContactId => 1, $primaryContactId => 1));
                             $relationIds = array('contact' => $householdId);
                             CRM_Contact_BAO_Relationship::create($relationParams, $relationIds);
                         }
                     }
                 }
             }
         }
     }
     if ($this->_updateWithId) {
         return $this->_retCode;
     }
     //dupe checking
     if (is_a($newContact, CRM_Core_Error)) {
         $code = $newContact->_errors[0]['code'];
         if ($code == CRM_CORE_ERROR_DUPLICATE_CONTACT) {
             $urls = array();
             foreach ($newContact->_errors[0]['params'] as $cid) {
                 $urls[] = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $cid, true);
             }
             $url_string = implode("\n", $urls);
             array_unshift($values, $url_string);
             /* If we duplicate more than one record, skip no matter what */
             if (count($newContact->_errors[0]['params']) > 1) {
                 array_unshift($values, ts('Record duplicates multiple contacts'));
                 return CRM_IMPORT_PARSER_ERROR;
             }
             /* Params only had one id, so shift it out */
             $contactId = array_shift($newContact->_errors[0]['params']);
             if ($onDuplicate == CRM_IMPORT_PARSER_DUPLICATE_REPLACE) {
                 $newContact = crm_replace_contact_formatted($contactId, $formatted);
             } else {
                 if ($onDuplicate == CRM_IMPORT_PARSER_DUPLICATE_UPDATE) {
                     $newContact = crm_update_contact_formatted($contactId, $formatted, true);
                 } else {
                     if ($onDuplicate == CRM_IMPORT_PARSER_DUPLICATE_FILL) {
                         $newContact = crm_update_contact_formatted($contactId, $formatted, false);
                     }
                 }
             }
             // else skip does nothing and just returns an error code.
             if ($newContact && !is_a($newContact, CRM_Core_Error)) {
                 $this->_newContacts[] = $newContact->id;
             }
             //CRM-262 No Duplicate Checking
             if ($onDuplicate == CRM_IMPORT_PARSER_DUPLICATE_SKIP) {
                 return CRM_IMPORT_PARSER_DUPLICATE;
             }
             return CRM_IMPORT_PARSER_VALID;
         } else {
             /* Not a dupe, so we had an error */
             array_unshift($values, $newContact->_errors[0]['message']);
             return CRM_IMPORT_PARSER_ERROR;
         }
     }
     if ($newContact && !is_a($newContact, CRM_Core_Error)) {
         $this->_newContacts[] = $newContact->id;
     }
     return CRM_IMPORT_PARSER_VALID;
 }