/** * Determine if an API request should be treated as transactional * * @param \Civi\API\Provider\ProviderInterface $apiProvider * @param array $apiRequest * @return bool */ public function isTransactional($apiProvider, $apiRequest) { if (isset($apiRequest['params']['is_transactional'])) { return \CRM_Utils_String::strtobool($apiRequest['params']['is_transactional']); } return strtolower($apiRequest['action']) == 'create' || strtolower($apiRequest['action']) == 'delete' || strtolower($apiRequest['action']) == 'submit'; }
/** * 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; } }
/** * @param $input * @param bool $expected * * @dataProvider booleanDataProvider */ public function testStrToBool($input, $expected) { $actual = CRM_Utils_String::strtobool($input); $this->assertTrue($expected === $actual); }
/** * 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(); $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'); $customDataType = !empty($params['contact_type']) ? $params['contact_type'] : 'Contribution'; $customFields = CRM_Core_BAO_CustomField::getFields($customDataType); //CRM-10994 if (isset($params['total_amount']) && $params['total_amount'] == 0) { $params['total_amount'] = '0.00'; } foreach ($params as $key => $val) { if ($val) { switch ($key) { case 'receive_date': case 'cancel_date': case 'receipt_date': case 'thankyou_date': $params[$key] = CRM_Utils_Date::formatDate($params[$key], $dateType); 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_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); } } } } //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_Import_Parser::DUPLICATE_SKIP && (!empty($paramValues['contribution_contact_id']) || !empty($paramValues['external_identifier']))) { $paramValues['contact_type'] = $this->_contactType; } elseif ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE && (!empty($paramValues['contribution_id']) || !empty($values['trxn_id']) || !empty($paramValues['invoice_id']))) { $paramValues['contact_type'] = $this->_contactType; } elseif (!empty($params['soft_credit'])) { $paramValues['contact_type'] = $this->_contactType; } elseif (!empty($paramValues['pledge_payment'])) { $paramValues['contact_type'] = $this->_contactType; } //need to pass $onDuplicate to check import mode. if (!empty($paramValues['pledge_payment'])) { $paramValues['onDuplicate'] = $onDuplicate; } require_once 'CRM/Utils/DeprecatedUtils.php'; $formatError = _civicrm_api3_deprecated_formatted_param($paramValues, $formatted, TRUE, $onDuplicate); 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_Import_Parser::ERROR; } if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) { $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, NULL, 'Contribution'); } else { //fix for CRM-2219 - Update Contribution // onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE if (!empty($paramValues['invoice_id']) || !empty($paramValues['trxn_id']) || !empty($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, $formatted['id'], 'Contribution'); //process note if (!empty($paramValues['note'])) { $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 (!empty($formatted['soft_credit'])) { $dupeSoftCredit = array('contact_id' => $formatted['soft_credit'], 'contribution_id' => $ids['contribution']); //Delete all existing soft Contribution from contribution_soft table for pcp_id is_null $existingSoftCredit = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dupeSoftCredit['contribution_id']); if (isset($existingSoftCredit['soft_credit']) && !empty($existingSoftCredit['soft_credit'])) { foreach ($existingSoftCredit['soft_credit'] as $key => $existingSoftCreditValues) { if (!empty($existingSoftCreditValues['soft_credit_id'])) { $deleteParams = array('id' => $existingSoftCreditValues['soft_credit_id'], 'pcp_id' => NULL); CRM_Contribute_BAO_ContributionSoft::del($deleteParams); } } } } $newContribution = CRM_Contribute_BAO_Contribution::create($formatted, $ids); $this->_newContributions[] = $newContribution->id; //return soft valid since we need to show how soft credits were added if (!empty($formatted['soft_credit'])) { return CRM_Contribute_Import_Parser::SOFT_CREDIT; } // process pledge payment assoc w/ the contribution return self::processPledgePayments($formatted); return CRM_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_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 'CRM/Utils/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_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_Import_Parser::DUPLICATE; } } else { array_unshift($values, $newContribution['error_message']); return CRM_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 (!empty($formatted['soft_credit'])) { return CRM_Contribute_Import_Parser::SOFT_CREDIT; } // process pledge payment assoc w/ the contribution return self::processPledgePayments($formatted); 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 = NULL; 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($paramValues['external_identifier'])) { $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 ID:' . $paramValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']); return CRM_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_Import_Parser::DUPLICATE; } } else { array_unshift($values, $newContribution['error_message']); return CRM_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 (!empty($formatted['soft_credit'])) { return CRM_Contribute_Import_Parser::SOFT_CREDIT; } // process pledge payment assoc w/ the contribution return self::processPledgePayments($formatted); return CRM_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_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; } }
/** * update the custom calue for a given contact id and field id * * @param int $contactId contact id * @param int $cfId custom field id * @param string $value the value to set the field * * @return void * @access public * @static */ function updateValue($contactId, $cfId, $value) { $customValue =& new CRM_Core_BAO_CustomValue(); $customValue->custom_field_id = $cfId; $customValue->entity_table = 'civicrm_contact'; $customValue->entity_id = $contactId; $customValue->find(true); $cf =& new CRM_Core_BAO_CustomField(); $cf->id = $cfId; $cf->find(true); if ($cf->data_type == 'StateProvince') { $states =& CRM_Core_PseudoConstant::stateProvince(); if (CRM_Utils_Rule::integer($value)) { $customValue->int_data = $value; $customValue->char_data = CRM_Utils_Array::value($value, $states); } else { $customValue->int_data = CRM_Utils_Array::key($value, $states); $customValue->char_data = $value; } } elseif ($cf->data_type == 'Country') { $countries =& CRM_Core_PseudoConstant::country(); if (CRM_Utils_Rule::integer($value)) { $customValue->int_data = $value; $customValue->char_data = CRM_Utils_Array::value($value, $countries); } else { $customValue->int_data = CRM_Utils_Array::key($value, $countries); $customValue->char_data = $value; } } else { $isBool = false; $field = $customValue->getField($isBool, $cf); if ($isBool) { $value = CRM_Utils_String::strtobool($value); } $customValue->{$field} = $value; } $customValue->save(); }
/** * Determine if caller wants us to *always* rollback. * * @param \Civi\API\Provider\ProviderInterface $apiProvider * The API provider responsible for this request. * @param array $apiRequest * The full API request. * @return bool */ public function isForceRollback($apiProvider, $apiRequest) { // FIXME: When APIv3 uses better parsing, only one check will be needed. if (isset($apiRequest['params']['options']['force_rollback'])) { return \CRM_Utils_String::strtobool($apiRequest['params']['options']['force_rollback']); } if (isset($apiRequest['options']['force_rollback'])) { return \CRM_Utils_String::strtobool($apiRequest['options']['force_rollback']); } return FALSE; }
/** * @return array */ public function run() { $config =& CRM_Core_Config::singleton(); // do check for geocoding. $processGeocode = FALSE; if (empty($config->geocodeMethod)) { if (CRM_Utils_String::strtobool($this->geocoding) === TRUE) { $this->returnMessages[] = ts('Error: You need to set a mapping provider under Administer > System Settings > Mapping and Geocoding'); $this->returnError = 1; $this->returnResult(); } } else { $processGeocode = TRUE; // user might want to over-ride. if (CRM_Utils_String::strtobool($this->geocoding) === FALSE) { $processGeocode = FALSE; } } // do check for parse street address. $parseAddress = FALSE; $parseAddress = CRM_Utils_Array::value('street_address_parsing', CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'address_options'), FALSE); $parseStreetAddress = FALSE; if (!$parseAddress) { if (CRM_Utils_String::strtobool($this->parse) === TRUE) { $this->returnMessages[] = ts('Error: You need to enable Street Address Parsing under Administer > Localization > Address Settings.'); $this->returnError = 1; return $this->returnResult(); } } else { $parseStreetAddress = TRUE; // user might want to over-ride. if (CRM_Utils_String::strtobool($this->parse) === FALSE) { $parseStreetAddress = FALSE; } } // don't process. if (!$parseStreetAddress && !$processGeocode) { $this->returnMessages[] = ts('Error: Both Geocode mapping as well as Street Address Parsing are disabled. You must configure one or both options to use this script.'); $this->returnError = 1; return $this->returnResult(); } // do check for parse street address. return $this->processContacts($config, $processGeocode, $parseStreetAddress); }
/** * Determine if modifications are allowed on the case-type * * @param int $caseTypeId * @return bool * TRUE if the definition can be modified */ public static function isForkable($caseTypeId) { $caseTypeName = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseType', $caseTypeId, 'name', 'id', TRUE); if ($caseTypeName) { // if file-based definition explicitly disables "forkable" option, then don't allow changes to definition $fileDefinition = CRM_Case_XMLRepository::singleton()->retrieveFile($caseTypeName); if ($fileDefinition && isset($fileDefinition->forkable)) { return CRM_Utils_String::strtobool((string) $fileDefinition->forkable); } } return TRUE; }
function _crm_update_contact($contact, $values, $overwrite = true) { // first check to make sure the location arrays sync up $param = array("contact_id" => $contact->id); $contact = crm_get_contact($param); $locMatch = _crm_location_match($contact, $values); if (!$locMatch) { return _crm_error('Cannot update contact location'); } // it is possible that an contact type object record does not exist // if the contact_type_object is null etc, if so we create one if ($contact->contact_type_object == null) { require_once str_replace('_', DIRECTORY_SEPARATOR, "CRM_Contact_BAO_" . $contact->contact_type) . ".php"; eval('$contact->contact_type_object =& new CRM_Contact_BAO_' . $contact->contact_type . '( );'); $contact->contact_type_object->contact_id = $contact->id; } $sortNameArray = array(); // fix sort_name and display_name if ($contact->contact_type == 'Individual') { if ($overwrite || !isset($contact->contact_type_object->first_name)) { $firstName = CRM_Utils_Array::value('first_name', $values); } else { $firstName = null; } if (!$firstName) { $firstName = isset($contact->contact_type_object->first_name) ? $contact->contact_type_object->first_name : ''; } if ($overwrite || !isset($contact->contact_type_object->middle_name)) { $middleName = CRM_Utils_Array::value('middle_name', $values); } else { $middleName = null; } if (!$middleName) { $middleName = isset($contact->contact_type_object->middle_name) ? $contact->contact_type_object->middle_name : ''; } if ($overwrite || !isset($contact->contact_type_object->last_name)) { $lastName = CRM_Utils_Array::value('last_name', $values); } else { $lastName = null; } if (!$lastName) { $lastName = isset($contact->contact_type_object->last_name) ? $contact->contact_type_object->last_name : ''; } if ($overwrite || !isset($contact->contact_type_object->prefix_id)) { $prefix = CRM_Utils_Array::value('prefix', $values); } else { $prefix = null; } if (!$prefix) { if (isset($contact->contact_type_object->prefix_id)) { $prefix =& new CRM_Core_DAO_IndividualPrefix(); $prefix->id = $contact->contact_type_object->prefix_id; $prefix->find(); $prefix->fetch(); $prefix = $prefix->name; } else { $prefix = ""; } } if ($overwrite || !isset($contact->contact_type_object->suffix_id)) { $suffix = CRM_Utils_Array::value('suffix', $values); } else { $suffix = null; } if (!$suffix) { if (isset($contact->contact_type_object->suffix_id)) { $suffix =& new CRM_Core_DAO_IndividualSuffix(); $suffix->id = $contact->contact_type_object->suffix_id; $suffix->find(); $suffix->fetch(); $suffix = $suffix->name; } else { $suffix = ""; } } if ($overwrite) { $gender = CRM_Utils_Array::value('gender', $values); } else { $gender = null; } if ($gender) { $genderDao =& new CRM_Core_DAO_Gender(); $genderDao->name = $gender; $genderDao->find(true); $values['gender_id'] = $genderDao->id; } if ($lastName != "" && $firstName != "") { $values['sort_name'] = "{$lastName}, {$firstName}"; } else { if ($lastName != "") { $values['sort_name'] = "{$lastName}"; } else { if ($firstName != "") { $values['sort_name'] = "{$firstName}"; } } } $values['display_name'] = "{$prefix} {$firstName} {$middleName} {$lastName} {$suffix} "; } else { if ($contact->contact_type == 'Household') { if ($overwrite || !isset($contact->contact_type_object->household_name)) { $householdName = CRM_Utils_Array::value('household_name', $values); } else { $householdName = null; } if (!$householdName) { $householdName = isset($contact->contact_type_object->household_name) ? $contact->contact_type_object->household_name : ''; } $values['sort_name'] = $householdName; } else { if ($overwrite || !isset($contact->contact_type_object->organization_name)) { $organizationName = CRM_Utils_Array::value('organization_name', $values); } else { $organizationName = null; } if (!$organizationName) { $organizationName = isset($contact->contact_type_object->organization_name) ? $contact->contact_type_object->organization_name : ''; } $values['sort_name'] = $organizationName; } } _crm_update_object($contact, $values); _crm_update_object($contact->contact_type_object, $values); if (!isset($contact->location)) { $contact->location = array(); } if (!array_key_exists(1, $contact->location) || empty($contact->location[1])) { $contact->location[1] =& new CRM_Core_BAO_Location(); } $primary_location = null; foreach ($contact->location as $key => $loc) { if ($loc->is_primary) { $primary_location = $key; break; } } if (is_array($values['location'])) { foreach ($values['location'] as $updateLocation) { $emptyBlock = $contactLocationBlock = null; /* Scan the location array for the correct block to update */ foreach ($contact->location as $key => $loc) { if ($loc->location_type_id == $updateLocation['location_type_id']) { $contactLocationBlock = $key; break; } else { if (!isset($loc->location_type_id)) { $emptyBlock = $key; } } } if ($contactLocationBlock == null) { if ($emptyBlock != null) { $contactLocationBlock = $emptyBlock; } else { /* no matching blocks and no empty blocks, make a new one */ $contact->location[] =& new CRM_Core_BAO_Location(); $contactLocationBlock = count($contact->location); } } $updateLocation['entity_id'] = $contact->id; $updateLocation['entity_table'] = CRM_Contact_BAO_Contact::getTableName(); /* If we're not overwriting, copy old data back before updating */ if (!$overwrite) { _crm_update_from_object($contact->location[$contactLocationBlock], $updateLocation, true); } /* Make sure we only have one primary location */ if ($primary_location == null && $updateLocation['is_primary']) { $primary_location = $contactLocationBlock; } else { if ($primary_location != $contactLocationBlock) { $updateLocation['is_primary'] = false; } } _crm_update_object($contact->location[$contactLocationBlock], $updateLocation); if (!isset($contact->location[$contactLocationBlock]->address)) { $contact->location[$contactLocationBlock]->address =& new CRM_Core_BAO_Address(); } $updateLocation['address']['location_id'] = $contact->location[$contactLocationBlock]->id; if ($updateLocation['address']['state_province']) { $state_province =& new CRM_Core_DAO_StateProvince(); $state_province->name = $updateLocation['address']['state_province']; if (!$state_province->find(true)) { $state_province->name = null; $state_province->abbreviation = $updateLocation['address']['state_province']; $state_province->find(true); } $updateLocation['address']['state_province_id'] = $state_province->id; } if ($updateLocation['address']['country']) { $country =& new CRM_Core_DAO_Country(); $country->name = $updateLocation['address']['country']; if (!$country->find(true)) { $country->name = null; $country->iso_code = $updateLocation['address']['country']; $country->find(true); } $updateLocation['address']['country_id'] = $country->id; } if (!$overwrite) { _crm_update_from_object($contact->location[$contactLocationBlock]->address, $updateLocation['address'], true); } _crm_update_object($contact->location[$contactLocationBlock]->address, $updateLocation['address']); $blocks = array('Email', 'IM'); foreach ($blocks as $block) { $name = strtolower($block); if (!is_array($updateLocation[$name])) { continue; } if (!isset($contact->location[$contactLocationBlock]->{$name})) { $contact->location[$contactLocationBlock]->{$name} = array(); } $primary = null; foreach ($contact->location[$contactLocationBlock]->{$name} as $key => $value) { if ($value->is_primary) { $primary = $key; break; } } $propertyBlock = 1; foreach ($updateLocation[$name] as $property) { if (!isset($contact->location[$contactLocationBlock]->{$name}[$propertyBlock])) { require_once str_replace('_', DIRECTORY_SEPARATOR, "CRM_Core_BAO_" . $block) . ".php"; eval('$contact->location[$contactLocationBlock]->{$name}[$propertyBlock] =& new CRM_Core_BAO_' . $block . '( );'); } $property['location_id'] = $contact->location[$contactLocationBlock]->id; if (!$overwrite) { _crm_update_from_object($contact->location[$contactLocationBlock]->{$name}[$propertyBlock], $property, true); } if ($primary == null && $property['is_primary']) { $primary = $propertyBlock; } else { if ($primary != $propertyBlock) { $property['is_primary'] = false; } } _crm_update_object($contact->location[$contactLocationBlock]->{$name}[$propertyBlock], $property); $propertyBlock++; } } /* handle multiple phones */ if (is_array($updateLocation['phone'])) { if (!isset($contact->location[$contactLocationBlock]->phone)) { $contact->location[$contactLocationBlock]->phone = array(); } $primary_phone = null; foreach ($contact->location[$contactLocationBlock]->phone as $key => $value) { if ($value->is_primary) { $primary_phone = $key; break; } } foreach ($updateLocation['phone'] as $phone) { /* scan through the contact record for matching phone type at this location */ $contactPhoneBlock = null; foreach ($contact->location[$contactLocationBlock]->phone as $key => $contactPhoneBlock) { if ($contactPhoneBlock->phone_type_id == $phone['phone_type_id']) { $contactPhoneBlock = $key; break; } } if ($contactPhoneBlock == null) { if (empty($contact->location[$contactLocationBlock]->phone)) { $contactPhoneBlock = 1; } else { $contactPhoneBlock = count($contact->location[$contactLocationBlock]->phone) + 1; } $contact->location[$contactLocationBlock]->phone[$contactPhoneBlock] =& new CRM_Core_BAO_Phone(); } $phone['location_id'] = $contact->location[$contactLocationBlock]->id; if (!$overwrite) { _crm_update_from_object($contact->location[$contactLocationBlock]->phone[$contactPhoneBlock], $phone, true); } if ($primary_phone == null && $phone['is_primary']) { $primary_phone = $contactPhoneBlock; } else { if ($primary_phone != $contactPhoneBlock) { $phone['is_primary'] = false; } } _crm_update_object($contact->location[$contactLocationBlock]->phone[$contactPhoneBlock], $phone); } } } } /* Custom data */ if (is_array($values['custom'])) { foreach ($values['custom'] as $customValue) { /* get the field for the data type */ $field = CRM_Core_BAO_CustomValue::typeToField($customValue['type']); if (!$field) { /* FIXME failure! */ continue; } /* adjust the value if it's boolean */ if ($customValue['type'] == 'Boolean') { $value = CRM_Utils_String::strtobool($customValue['value']); } else { $value = $customValue['value']; } /* look for a matching existing custom value */ $match = false; foreach ($contact->custom_values as $cv) { if ($cv->custom_field_id == $customValue['custom_field_id']) { /* match */ $match = true; if ($overwrite) { $cv->{$field} = $value; $cv->save(); break; } } } if (!$match) { /* no match, so create a new CustomValue */ $cvParams = array('entity_table' => 'civicrm_contact', 'entity_id' => $contact->id, 'value' => $value, 'type' => $customValue['type'], 'custom_field_id' => $customValue['custom_field_id']); CRM_Core_BAO_CustomValue::create($cvParams); } } } return $contact; }
/** * 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(); // 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]); } else { if ($customFields[$customFieldID]['data_type'] == 'Boolean') { $params[$key] = CRM_Utils_String::strtoboolstr($val); } } } } } //date-Format part ends static $indieFields = null; if ($indieFields == null) { require_once 'CRM/Contribute/DAO/Contribution.php'; $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 && ($paramValues['contribution_contact_id'] || $paramValues['external_identifier'])) { $paramValues['contact_type'] = $this->_contactType; } else { if ($onDuplicate == CRM_Contribute_Import_Parser::DUPLICATE_UPDATE && ($paramValues['contribution_id'] || $values['trxn_id'] || $paramValues['invoice_id'])) { $paramValues['contact_type'] = $this->_contactType; } else { if (!empty($params['soft_credit'])) { $paramValues['contact_type'] = $this->_contactType; } else { if (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; } $formatError = _civicrm_contribute_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; } else { if (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 ($paramValues['invoice_id'] || $paramValues['trxn_id'] || $paramValues['contribution_id']) { require_once 'CRM/Contribute/BAO/Contribution.php'; $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 ($paramValues['note']) { $noteID = array(); $contactID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'contact_id'); require_once 'CRM/Core/BAO/Note.php'; $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); $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; } //retrieve contact id using contact dedupe rule $error = civicrm_check_contact_dedupe($paramValues); 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 contribution was not imported"); return CRM_Contribute_Import_Parser::ERROR; } else { $cid = $matchedIDs[0]; $formatted['contact_id'] = $cid; $newContribution = civicrm_contribution_format_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']; //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'); 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_Contribute_Import_Parser::ERROR; } } else { if ($paramValues['external_identifier']) { $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_contribution_format_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']; //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; } }