3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
27 require_once 'CRM/Utils/DeprecatedUtils.php';
28 require_once 'api/v3/utils.php';
33 * @copyright CiviCRM LLC (c) 2004-2019
37 * class to parse contact csv files
39 class CRM_Contact_Import_Parser_Contact
extends CRM_Contact_Import_Parser
{
40 protected $_mapperKeys = [];
41 protected $_mapperLocType = [];
42 protected $_mapperPhoneType;
43 protected $_mapperImProvider;
44 protected $_mapperWebsiteType;
45 protected $_mapperRelated;
46 protected $_mapperRelatedContactType;
47 protected $_mapperRelatedContactDetails;
48 protected $_mapperRelatedContactEmailType;
49 protected $_mapperRelatedContactImProvider;
50 protected $_mapperRelatedContactWebsiteType;
51 protected $_relationships;
53 protected $_emailIndex;
54 protected $_firstNameIndex;
55 protected $_lastNameIndex;
57 protected $_householdNameIndex;
58 protected $_organizationNameIndex;
60 protected $_allEmails;
62 protected $_phoneIndex;
65 * Is update only permitted on an id match.
67 * Note this historically was true for when id or external identifier was
68 * present. However, CRM-17275 determined that a dedupe-match could over-ride
69 * external identifier.
73 protected $_updateWithId;
76 protected $_externalIdentifierIndex;
77 protected $_allExternalIdentifiers;
78 protected $_parseStreetAddress;
81 * Array of successfully imported contact id's
85 protected $_newContacts;
92 protected $_lineCount;
95 * Array of successfully imported related contact id's
99 protected $_newRelatedContacts;
102 * Array of all the contacts whose street addresses are not parsed.
103 * of this import process
106 protected $_unparsedStreetAddressContacts;
111 * @param array $mapperKeys
112 * @param array $mapperLocType
113 * @param array $mapperPhoneType
114 * @param array $mapperImProvider
115 * @param array $mapperRelated
116 * @param array $mapperRelatedContactType
117 * @param array $mapperRelatedContactDetails
118 * @param array $mapperRelatedContactLocType
119 * @param array $mapperRelatedContactPhoneType
120 * @param array $mapperRelatedContactImProvider
121 * @param array $mapperWebsiteType
122 * @param array $mapperRelatedContactWebsiteType
124 public function __construct(
125 &$mapperKeys, $mapperLocType = [], $mapperPhoneType = [], $mapperImProvider = [], $mapperRelated = [], $mapperRelatedContactType = [], $mapperRelatedContactDetails = [], $mapperRelatedContactLocType = [], $mapperRelatedContactPhoneType = [], $mapperRelatedContactImProvider = [],
126 $mapperWebsiteType = [], $mapperRelatedContactWebsiteType = []
128 parent
::__construct();
129 $this->_mapperKeys
= &$mapperKeys;
130 $this->_mapperLocType
= &$mapperLocType;
131 $this->_mapperPhoneType
= &$mapperPhoneType;
132 $this->_mapperWebsiteType
= $mapperWebsiteType;
133 // get IM service provider type id for contact
134 $this->_mapperImProvider
= &$mapperImProvider;
135 $this->_mapperRelated
= &$mapperRelated;
136 $this->_mapperRelatedContactType
= &$mapperRelatedContactType;
137 $this->_mapperRelatedContactDetails
= &$mapperRelatedContactDetails;
138 $this->_mapperRelatedContactLocType
= &$mapperRelatedContactLocType;
139 $this->_mapperRelatedContactPhoneType
= &$mapperRelatedContactPhoneType;
140 $this->_mapperRelatedContactWebsiteType
= $mapperRelatedContactWebsiteType;
141 // get IM service provider type id for related contact
142 $this->_mapperRelatedContactImProvider
= &$mapperRelatedContactImProvider;
146 * The initializer code, called before processing.
148 public function init() {
149 $contactFields = CRM_Contact_BAO_Contact
::importableFields($this->_contactType
);
150 // exclude the address options disabled in the Address Settings
151 $fields = CRM_Core_BAO_Address
::validateAddressOptions($contactFields);
154 //supporting import for contact subtypes
156 if (!empty($this->_contactSubType
)) {
157 //custom fields for sub type
158 $subTypeFields = CRM_Core_BAO_CustomField
::getFieldsForImport($this->_contactSubType
);
160 if (!empty($subTypeFields)) {
161 foreach ($subTypeFields as $customSubTypeField => $details) {
162 $fields[$customSubTypeField] = $details;
167 //Relationship importables
168 $this->_relationships
= $relations
169 = CRM_Contact_BAO_Relationship
::getContactRelationshipType(
170 NULL, NULL, NULL, $this->_contactType
,
171 FALSE, 'label', TRUE, $this->_contactSubType
175 foreach ($relations as $key => $var) {
176 list($type) = explode('_', $key);
177 $relationshipType[$key]['title'] = $var;
178 $relationshipType[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
179 $relationshipType[$key]['import'] = TRUE;
180 $relationshipType[$key]['relationship_type_id'] = $type;
181 $relationshipType[$key]['related'] = TRUE;
184 if (!empty($relationshipType)) {
185 $fields = array_merge($fields, [
187 'title' => ts('- related contact info -'),
189 ], $relationshipType);
192 foreach ($fields as $name => $field) {
193 $this->addField($name, $field['title'], CRM_Utils_Array
::value('type', $field), CRM_Utils_Array
::value('headerPattern', $field), CRM_Utils_Array
::value('dataPattern', $field), CRM_Utils_Array
::value('hasLocationType', $field));
196 $this->_newContacts
= [];
198 $this->setActiveFields($this->_mapperKeys
);
199 $this->setActiveFieldLocationTypes($this->_mapperLocType
);
200 $this->setActiveFieldPhoneTypes($this->_mapperPhoneType
);
201 $this->setActiveFieldWebsiteTypes($this->_mapperWebsiteType
);
202 //set active fields of IM provider of contact
203 $this->setActiveFieldImProviders($this->_mapperImProvider
);
206 $this->setActiveFieldRelated($this->_mapperRelated
);
207 $this->setActiveFieldRelatedContactType($this->_mapperRelatedContactType
);
208 $this->setActiveFieldRelatedContactDetails($this->_mapperRelatedContactDetails
);
209 $this->setActiveFieldRelatedContactLocType($this->_mapperRelatedContactLocType
);
210 $this->setActiveFieldRelatedContactPhoneType($this->_mapperRelatedContactPhoneType
);
211 $this->setActiveFieldRelatedContactWebsiteType($this->_mapperRelatedContactWebsiteType
);
212 //set active fields of IM provider of related contact
213 $this->setActiveFieldRelatedContactImProvider($this->_mapperRelatedContactImProvider
);
215 $this->_phoneIndex
= -1;
216 $this->_emailIndex
= -1;
217 $this->_firstNameIndex
= -1;
218 $this->_lastNameIndex
= -1;
219 $this->_householdNameIndex
= -1;
220 $this->_organizationNameIndex
= -1;
221 $this->_externalIdentifierIndex
= -1;
224 foreach ($this->_mapperKeys
as $key) {
225 if (substr($key, 0, 5) == 'email' && substr($key, 0, 14) != 'email_greeting') {
226 $this->_emailIndex
= $index;
227 $this->_allEmails
= [];
229 if (substr($key, 0, 5) == 'phone') {
230 $this->_phoneIndex
= $index;
232 if ($key == 'first_name') {
233 $this->_firstNameIndex
= $index;
235 if ($key == 'last_name') {
236 $this->_lastNameIndex
= $index;
238 if ($key == 'household_name') {
239 $this->_householdNameIndex
= $index;
241 if ($key == 'organization_name') {
242 $this->_organizationNameIndex
= $index;
245 if ($key == 'external_identifier') {
246 $this->_externalIdentifierIndex
= $index;
247 $this->_allExternalIdentifiers
= [];
252 $this->_updateWithId
= FALSE;
253 if (in_array('id', $this->_mapperKeys
) ||
($this->_externalIdentifierIndex
>= 0 && in_array($this->_onDuplicate
, [
254 CRM_Import_Parser
::DUPLICATE_UPDATE
,
255 CRM_Import_Parser
::DUPLICATE_FILL
,
257 $this->_updateWithId
= TRUE;
260 $this->_parseStreetAddress
= CRM_Utils_Array
::value('street_address_parsing', CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'address_options'), FALSE);
264 * Handle the values in mapField mode.
266 * @param array $values
267 * The array of values belonging to this line.
271 public function mapField(&$values) {
272 return CRM_Import_Parser
::VALID
;
276 * Handle the values in preview mode.
278 * @param array $values
279 * The array of values belonging to this line.
282 * the result of this processing
284 public function preview(&$values) {
285 return $this->summary($values);
289 * Handle the values in summary mode.
291 * @param array $values
292 * The array of values belonging to this line.
295 * the result of this processing
297 public function summary(&$values) {
298 $erroneousField = NULL;
299 $response = $this->setActiveFieldValues($values, $erroneousField);
301 $errorMessage = NULL;
302 $errorRequired = FALSE;
303 switch ($this->_contactType
) {
306 if ($this->_firstNameIndex
< 0 ||
empty($values[$this->_firstNameIndex
])) {
307 $errorRequired = TRUE;
308 $missingNames[] = ts('First Name');
310 if ($this->_lastNameIndex
< 0 ||
empty($values[$this->_lastNameIndex
])) {
311 $errorRequired = TRUE;
312 $missingNames[] = ts('Last Name');
314 if ($errorRequired) {
315 $and = ' ' . ts('and') . ' ';
316 $errorMessage = ts('Missing required fields:') . ' ' . implode($and, $missingNames);
321 if ($this->_householdNameIndex
< 0 ||
empty($values[$this->_householdNameIndex
])) {
322 $errorRequired = TRUE;
323 $errorMessage = ts('Missing required fields:') . ' ' . ts('Household Name');
328 if ($this->_organizationNameIndex
< 0 ||
empty($values[$this->_organizationNameIndex
])) {
329 $errorRequired = TRUE;
330 $errorMessage = ts('Missing required fields:') . ' ' . ts('Organization Name');
335 $statusFieldName = $this->_statusFieldName
;
337 if ($this->_emailIndex
>= 0) {
338 /* If we don't have the required fields, bail */
340 if ($this->_contactType
== 'Individual' && !$this->_updateWithId
) {
341 if ($errorRequired && empty($values[$this->_emailIndex
])) {
343 $errorMessage .= ' ' . ts('OR') . ' ' . ts('Email Address');
346 $errorMessage = ts('Missing required field:') . ' ' . ts('Email Address');
348 array_unshift($values, $errorMessage);
349 $importRecordParams = [
350 $statusFieldName => 'ERROR',
351 "${statusFieldName}Msg" => $errorMessage,
353 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
355 return CRM_Import_Parser
::ERROR
;
359 $email = CRM_Utils_Array
::value($this->_emailIndex
, $values);
361 /* If the email address isn't valid, bail */
363 if (!CRM_Utils_Rule
::email($email)) {
364 $errorMessage = ts('Invalid Email address');
365 array_unshift($values, $errorMessage);
366 $importRecordParams = [
367 $statusFieldName => 'ERROR',
368 "${statusFieldName}Msg" => $errorMessage,
370 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
372 return CRM_Import_Parser
::ERROR
;
375 /* otherwise, count it and move on */
376 $this->_allEmails
[$email] = $this->_lineCount
;
379 elseif ($errorRequired && !$this->_updateWithId
) {
381 $errorMessage .= ' ' . ts('OR') . ' ' . ts('Email Address');
384 $errorMessage = ts('Missing required field:') . ' ' . ts('Email Address');
386 array_unshift($values, $errorMessage);
387 $importRecordParams = [
388 $statusFieldName => 'ERROR',
389 "${statusFieldName}Msg" => $errorMessage,
391 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
393 return CRM_Import_Parser
::ERROR
;
396 //check for duplicate external Identifier
397 $externalID = CRM_Utils_Array
::value($this->_externalIdentifierIndex
, $values);
399 /* If it's a dupe,external Identifier */
401 if ($externalDupe = CRM_Utils_Array
::value($externalID, $this->_allExternalIdentifiers
)) {
402 $errorMessage = ts('External ID conflicts with record %1', [1 => $externalDupe]);
403 array_unshift($values, $errorMessage);
404 $importRecordParams = [
405 $statusFieldName => 'ERROR',
406 "${statusFieldName}Msg" => $errorMessage,
408 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
409 return CRM_Import_Parser
::ERROR
;
411 //otherwise, count it and move on
412 $this->_allExternalIdentifiers
[$externalID] = $this->_lineCount
;
415 //Checking error in custom data
416 $params = &$this->getActiveFieldParams();
417 $params['contact_type'] = $this->_contactType
;
418 //date-format part ends
420 $errorMessage = NULL;
423 //add custom fields for contact sub type
425 if (!empty($this->_contactSubType
)) {
426 $csType = $this->_contactSubType
;
429 //checking error in custom data
430 $this->isErrorInCustomData($params, $errorMessage, $csType, $this->_relationships
);
432 //checking error in core data
433 $this->isErrorInCoreData($params, $errorMessage);
435 $tempMsg = "Invalid value for field(s) : $errorMessage";
436 // put the error message in the import record in the DB
437 $importRecordParams = [
438 $statusFieldName => 'ERROR',
439 "${statusFieldName}Msg" => $tempMsg,
441 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
442 array_unshift($values, $tempMsg);
443 $errorMessage = NULL;
444 return CRM_Import_Parser
::ERROR
;
447 //if user correcting errors by walking back
448 //need to reset status ERROR msg to null
449 //now currently we are having valid data.
450 $importRecordParams = [
451 $statusFieldName => 'NEW',
453 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
455 return CRM_Import_Parser
::VALID
;
459 * Get Array of all the fields that could potentially be part
464 public function getAllFields() {
465 return $this->_fields
;
469 * Handle the values in import mode.
471 * @param int $onDuplicate
472 * The code for what action to take on duplicates.
473 * @param array $values
474 * The array of values belonging to this line.
476 * @param bool $doGeocodeAddress
479 * the result of this processing
481 public function import($onDuplicate, &$values, $doGeocodeAddress = FALSE) {
482 $config = CRM_Core_Config
::singleton();
483 $this->_unparsedStreetAddressContacts
= [];
484 if (!$doGeocodeAddress) {
485 // CRM-5854, reset the geocode method to null to prevent geocoding
486 CRM_Utils_GeocodeProvider
::disableForSession();
489 // first make sure this is a valid line
490 //$this->_updateWithId = false;
491 $response = $this->summary($values);
492 $statusFieldName = $this->_statusFieldName
;
494 if ($response != CRM_Import_Parser
::VALID
) {
495 $importRecordParams = [
496 $statusFieldName => 'INVALID',
497 "${statusFieldName}Msg" => "Invalid (Error Code: $response)",
499 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
503 $params = &$this->getActiveFieldParams();
505 'contact_type' => $this->_contactType
,
508 static $contactFields = NULL;
509 if ($contactFields == NULL) {
510 $contactFields = CRM_Contact_DAO_Contact
::import();
513 //check if external identifier exists in database
514 if (!empty($params['external_identifier']) && (!empty($params['id']) ||
in_array($onDuplicate, [
515 CRM_Import_Parser
::DUPLICATE_SKIP
,
516 CRM_Import_Parser
::DUPLICATE_NOCHECK
,
519 $extIDResult = civicrm_api3('Contact', 'get', [
520 'external_identifier' => $params['external_identifier'],
522 'return' => ['id', 'contact_is_deleted'],
524 if (isset($extIDResult['id'])) {
525 // record with matching external identifier does exist.
526 $internalCid = $extIDResult['id'];
527 if ($internalCid != CRM_Utils_Array
::value('id', $params)) {
528 if ($extIDResult['values'][$internalCid]['contact_is_deleted'] == 1) {
529 // And it is deleted. What to do? If we skip it, they user
530 // will be under the impression that the record exists in
531 // the database, yet they won't be able to find it. If we
532 // don't skip it, the database will try to insert a new record
533 // with an external_identifier that is non-unique. So...
534 // we will update this contact to remove the external_identifier
535 // and let a new record be created.
536 $update_params = ['id' => $internalCid, 'external_identifier' => ''];
537 civicrm_api3('Contact', 'create', $update_params);
540 $errorMessage = ts('External ID already exists in Database.');
541 array_unshift($values, $errorMessage);
542 $importRecordParams = [
543 $statusFieldName => 'ERROR',
544 "${statusFieldName}Msg" => $errorMessage,
546 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
547 return CRM_Import_Parser
::DUPLICATE
;
553 if (!empty($this->_contactSubType
)) {
554 $params['contact_sub_type'] = $this->_contactSubType
;
557 if ($subType = CRM_Utils_Array
::value('contact_sub_type', $params)) {
558 if (CRM_Contact_BAO_ContactType
::isExtendsContactType($subType, $this->_contactType
, FALSE, 'label')) {
559 $subTypes = CRM_Contact_BAO_ContactType
::subTypePairs($this->_contactType
, FALSE, NULL);
560 $params['contact_sub_type'] = array_search($subType, $subTypes);
562 elseif (!CRM_Contact_BAO_ContactType
::isExtendsContactType($subType, $this->_contactType
)) {
563 $message = "Mismatched or Invalid Contact Subtype.";
564 array_unshift($values, $message);
565 return CRM_Import_Parser
::NO_MATCH
;
569 // Get contact id to format common data in update/fill mode,
570 // prioritising a dedupe rule check over an external_identifier check, but falling back on ext id.
571 if ($this->_updateWithId
&& empty($params['id'])) {
573 $possibleMatches = $this->getPossibleContactMatches($params);
575 catch (CRM_Core_Exception
$e) {
576 $errorMessage = $e->getMessage();
577 array_unshift($values, $errorMessage);
579 $importRecordParams = [
580 $statusFieldName => 'ERROR',
581 "${statusFieldName}Msg" => $errorMessage,
583 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
584 return CRM_Import_Parser
::ERROR
;
586 foreach ($possibleMatches as $possibleID) {
587 $params['id'] = $formatted['id'] = $possibleID;
590 //format common data, CRM-4062
591 $this->formatCommonData($params, $formatted, $contactFields);
593 $relationship = FALSE;
594 $createNewContact = TRUE;
595 // Support Match and Update Via Contact ID
596 if ($this->_updateWithId
&& isset($params['id'])) {
597 $createNewContact = FALSE;
598 // @todo - it feels like all the rows from here to the end of the IF
599 // could be removed in favour of a simple check for whether the contact_type & id match
600 // the call to the deprecated function seems to add no value other that to do an additional
601 // check for the contact_id & type.
602 $error = _civicrm_api3_deprecated_duplicate_formatted_contact($formatted);
603 if (CRM_Core_Error
::isAPIError($error, CRM_Core_ERROR
::DUPLICATE_CONTACT
)) {
604 if (is_array($error['error_message']['params'][0])) {
605 $matchedIDs = $error['error_message']['params'][0];
608 $matchedIDs = explode(',', $error['error_message']['params'][0]);
610 if (count($matchedIDs) >= 1) {
612 foreach ($matchedIDs as $contactId) {
613 if ($params['id'] == $contactId) {
614 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_type');
615 if ($formatted['contact_type'] == $contactType) {
616 //validation of subtype for update mode
618 $contactSubType = NULL;
619 if (!empty($params['contact_sub_type'])) {
620 $contactSubType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_sub_type');
623 if (!empty($contactSubType) && (!CRM_Contact_BAO_ContactType
::isAllowEdit($params['id'], $contactSubType) && $contactSubType != CRM_Utils_Array
::value('contact_sub_type', $formatted))) {
625 $message = "Mismatched contact SubTypes :";
626 array_unshift($values, $message);
628 $this->_retCode
= CRM_Import_Parser
::NO_MATCH
;
632 $this->_retCode
= CRM_Import_Parser
::VALID
;
636 $message = "Mismatched contact Types :";
637 array_unshift($values, $message);
639 $this->_retCode
= CRM_Import_Parser
::NO_MATCH
;
644 $message = "Mismatched contact IDs OR Mismatched contact Types :";
645 array_unshift($values, $message);
646 $this->_retCode
= CRM_Import_Parser
::NO_MATCH
;
652 if (!empty($params['id'])) {
653 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_type');
655 if ($formatted['contact_type'] == $contactType) {
656 //validation of subtype for update mode
658 $contactSubType = NULL;
659 if (!empty($params['contact_sub_type'])) {
660 $contactSubType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_sub_type');
663 if (!empty($contactSubType) && (!CRM_Contact_BAO_ContactType
::isAllowEdit($params['id'], $contactSubType) && $contactSubType != CRM_Utils_Array
::value('contact_sub_type', $formatted))) {
665 $message = "Mismatched contact SubTypes :";
666 array_unshift($values, $message);
667 $this->_retCode
= CRM_Import_Parser
::NO_MATCH
;
670 $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $params['id'], FALSE, $this->_dedupeRuleGroupID
);
671 $this->_retCode
= CRM_Import_Parser
::VALID
;
675 $message = "Mismatched contact Types :";
676 array_unshift($values, $message);
677 $this->_retCode
= CRM_Import_Parser
::NO_MATCH
;
681 // we should avoid multiple errors for single record
682 // since we have already retCode and we trying to force again.
683 if ($this->_retCode
!= CRM_Import_Parser
::NO_MATCH
) {
684 $message = "No contact found for this contact ID:" . $params['id'];
685 array_unshift($values, $message);
686 $this->_retCode
= CRM_Import_Parser
::NO_MATCH
;
692 //now we want to create new contact on update/fill also.
693 $createNewContact = TRUE;
697 if (isset($newContact) && is_a($newContact, 'CRM_Contact_BAO_Contact')) {
698 $relationship = TRUE;
700 elseif (is_a($error, 'CRM_Core_Error')) {
701 $newContact = $error;
702 $relationship = TRUE;
707 //now we create new contact in update/fill mode also.
709 if ($createNewContact ||
($this->_retCode
!= CRM_Import_Parser
::NO_MATCH
&& $this->_updateWithId
)) {
711 //CRM-4430, don't carry if not submitted.
712 foreach (['prefix_id', 'suffix_id', 'gender_id'] as $name) {
713 if (!empty($formatted[$name])) {
714 $options = CRM_Contact_BAO_Contact
::buildOptions($name, 'get');
715 if (!isset($options[$formatted[$name]])) {
716 $formatted[$name] = CRM_Utils_Array
::key((string) $formatted[$name], $options);
720 if ($this->_updateWithId
&& !empty($params['id'])) {
721 $contactID = $params['id'];
723 $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactID, TRUE, $this->_dedupeRuleGroupID
);
726 if (isset($newContact) && is_object($newContact) && ($newContact instanceof CRM_Contact_BAO_Contact
)) {
727 $relationship = TRUE;
728 $newContact = clone($newContact);
729 $contactID = $newContact->id
;
730 $this->_newContacts
[] = $contactID;
732 //get return code if we create new contact in update mode, CRM-4148
733 if ($this->_updateWithId
) {
734 $this->_retCode
= CRM_Import_Parser
::VALID
;
737 elseif (isset($newContact) && CRM_Core_Error
::isAPIError($newContact, CRM_Core_Error
::DUPLICATE_CONTACT
)) {
738 // if duplicate, no need of further processing
739 if ($onDuplicate == CRM_Import_Parser
::DUPLICATE_SKIP
) {
740 $errorMessage = "Skipping duplicate record";
741 array_unshift($values, $errorMessage);
742 $importRecordParams = [
743 $statusFieldName => 'DUPLICATE',
744 "${statusFieldName}Msg" => $errorMessage,
746 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
747 return CRM_Import_Parser
::DUPLICATE
;
750 $relationship = TRUE;
751 // CRM-10433/CRM-20739 - IDs could be string or array; handle accordingly
752 if (!is_array($dupeContactIDs = $newContact['error_message']['params'][0])) {
753 $dupeContactIDs = explode(',', $dupeContactIDs);
755 $dupeCount = count($dupeContactIDs);
756 $contactID = array_pop($dupeContactIDs);
757 // check to see if we had more than one duplicate contact id.
758 // if we have more than one, the record will be rejected below
759 if ($dupeCount == 1) {
760 // there was only one dupe, we will continue normally...
761 if (!in_array($contactID, $this->_newContacts
)) {
762 $this->_newContacts
[] = $contactID;
769 $currentImportID = end($values);
772 'contactID' => $contactID,
773 'importID' => $currentImportID,
774 'importTempTable' => $this->_tableName
,
775 'fieldHeaders' => $this->_mapperKeys
,
776 'fields' => $this->_activeFields
,
779 CRM_Utils_Hook
::import('Contact', 'process', $this, $hookParams);
783 $primaryContactId = NULL;
784 if (CRM_Core_Error
::isAPIError($newContact, CRM_Core_ERROR
::DUPLICATE_CONTACT
)) {
785 if ($dupeCount == 1 && CRM_Utils_Rule
::integer($contactID)) {
786 $primaryContactId = $contactID;
790 $primaryContactId = $newContact->id
;
793 if ((CRM_Core_Error
::isAPIError($newContact, CRM_Core_ERROR
::DUPLICATE_CONTACT
) ||
is_a($newContact, 'CRM_Contact_BAO_Contact')) && $primaryContactId) {
795 //relationship contact insert
796 foreach ($params as $key => $field) {
797 list($id, $first, $second) = CRM_Utils_System
::explode('_', $key, 3);
798 if (!($first == 'a' && $second == 'b') && !($first == 'b' && $second == 'a')) {
802 $relationType = new CRM_Contact_DAO_RelationshipType();
803 $relationType->id
= $id;
804 $relationType->find(TRUE);
805 $direction = "contact_sub_type_$second";
808 'contact_type' => $params[$key]['contact_type'],
811 //set subtype for related contact CRM-5125
812 if (isset($relationType->$direction)) {
813 //validation of related contact subtype for update mode
814 if ($relCsType = CRM_Utils_Array
::value('contact_sub_type', $params[$key]) && $relCsType != $relationType->$direction) {
815 $errorMessage = ts("Mismatched or Invalid contact subtype found for this related contact.");
816 array_unshift($values, $errorMessage);
817 return CRM_Import_Parser
::NO_MATCH
;
820 $formatting['contact_sub_type'] = $relationType->$direction;
823 $relationType->free();
825 $contactFields = NULL;
826 $contactFields = CRM_Contact_DAO_Contact
::import();
828 //Relation on the basis of External Identifier.
829 if (empty($params[$key]['id']) && !empty($params[$key]['external_identifier'])) {
830 $params[$key]['id'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $params[$key]['external_identifier'], 'id', 'external_identifier');
832 // check for valid related contact id in update/fill mode, CRM-4424
833 if (in_array($onDuplicate, [
834 CRM_Import_Parser
::DUPLICATE_UPDATE
,
835 CRM_Import_Parser
::DUPLICATE_FILL
,
836 ]) && !empty($params[$key]['id'])) {
837 $relatedContactType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $params[$key]['id'], 'contact_type');
838 if (!$relatedContactType) {
839 $errorMessage = ts("No contact found for this related contact ID: %1", [1 => $params[$key]['id']]);
840 array_unshift($values, $errorMessage);
841 return CRM_Import_Parser
::NO_MATCH
;
844 //validation of related contact subtype for update mode
846 $relatedCsType = NULL;
847 if (!empty($formatting['contact_sub_type'])) {
848 $relatedCsType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $params[$key]['id'], 'contact_sub_type');
851 if (!empty($relatedCsType) && (!CRM_Contact_BAO_ContactType
::isAllowEdit($params[$key]['id'], $relatedCsType) &&
852 $relatedCsType != CRM_Utils_Array
::value('contact_sub_type', $formatting))
854 $errorMessage = ts("Mismatched or Invalid contact subtype found for this related contact.") . ' ' . ts("ID: %1", [1 => $params[$key]['id']]);
855 array_unshift($values, $errorMessage);
856 return CRM_Import_Parser
::NO_MATCH
;
859 // get related contact id to format data in update/fill mode,
860 //if external identifier is present, CRM-4423
861 $formatting['id'] = $params[$key]['id'];
866 //format common data, CRM-4062
867 $this->formatCommonData($field, $formatting, $contactFields);
869 //do we have enough fields to create related contact.
870 $allowToCreate = $this->checkRelatedContactFields($key, $formatting);
872 if (!$allowToCreate) {
873 $errorMessage = ts('Related contact required fields are missing.');
874 array_unshift($values, $errorMessage);
875 return CRM_Import_Parser
::NO_MATCH
;
879 if (!empty($params[$key]['id'])) {
881 'contact_id' => $params[$key]['id'],
884 $relatedNewContact = CRM_Contact_BAO_Contact
::retrieve($contact, $defaults);
887 $relatedNewContact = $this->createContact($formatting, $contactFields, $onDuplicate, NULL, FALSE);
890 if (is_object($relatedNewContact) ||
($relatedNewContact instanceof CRM_Contact_BAO_Contact
)) {
891 $relatedNewContact = clone($relatedNewContact);
895 // To update/fill contact, get the matching contact Ids if duplicate contact found
896 // otherwise get contact Id from object of related contact
897 if (is_array($relatedNewContact) && civicrm_error($relatedNewContact)) {
898 if (CRM_Core_Error
::isAPIError($relatedNewContact, CRM_Core_ERROR
::DUPLICATE_CONTACT
)) {
899 $matchedIDs = $relatedNewContact['error_message']['params'][0];
900 if (!is_array($matchedIDs)) {
901 $matchedIDs = explode(',', $matchedIDs);
905 $errorMessage = $relatedNewContact['error_message'];
906 array_unshift($values, $errorMessage);
907 $importRecordParams = [
908 $statusFieldName => 'ERROR',
909 "${statusFieldName}Msg" => $errorMessage,
911 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
912 return CRM_Import_Parser
::ERROR
;
916 $matchedIDs[] = $relatedNewContact->id
;
918 // update/fill related contact after getting matching Contact Ids, CRM-4424
919 if (in_array($onDuplicate, [
920 CRM_Import_Parser
::DUPLICATE_UPDATE
,
921 CRM_Import_Parser
::DUPLICATE_FILL
,
923 //validation of related contact subtype for update mode
925 $relatedCsType = NULL;
926 if (!empty($formatting['contact_sub_type'])) {
927 $relatedCsType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $matchedIDs[0], 'contact_sub_type');
930 if (!empty($relatedCsType) && (!CRM_Contact_BAO_ContactType
::isAllowEdit($matchedIDs[0], $relatedCsType) && $relatedCsType != CRM_Utils_Array
::value('contact_sub_type', $formatting))) {
931 $errorMessage = ts("Mismatched or Invalid contact subtype found for this related contact.");
932 array_unshift($values, $errorMessage);
933 return CRM_Import_Parser
::NO_MATCH
;
936 $updatedContact = $this->createContact($formatting, $contactFields, $onDuplicate, $matchedIDs[0]);
939 static $relativeContact = [];
940 if (CRM_Core_Error
::isAPIError($relatedNewContact, CRM_Core_ERROR
::DUPLICATE_CONTACT
)) {
941 if (count($matchedIDs) >= 1) {
942 $relContactId = $matchedIDs[0];
943 //add relative contact to count during update & fill mode.
944 //logic to make count distinct by contact id.
945 if ($this->_newRelatedContacts ||
!empty($relativeContact)) {
946 $reContact = array_keys($relativeContact, $relContactId);
948 if (empty($reContact)) {
949 $this->_newRelatedContacts
[] = $relativeContact[] = $relContactId;
953 $this->_newRelatedContacts
[] = $relativeContact[] = $relContactId;
958 $relContactId = $relatedNewContact->id
;
959 $this->_newRelatedContacts
[] = $relativeContact[] = $relContactId;
962 if (CRM_Core_Error
::isAPIError($relatedNewContact, CRM_Core_ERROR
::DUPLICATE_CONTACT
) ||
($relatedNewContact instanceof CRM_Contact_BAO_Contact
)) {
963 //fix for CRM-1993.Checks for duplicate related contacts
964 if (count($matchedIDs) >= 1) {
965 //if more than one duplicate contact
966 //found, create relationship with first contact
967 // now create the relationship record
968 $relationParams = [];
970 'relationship_type_id' => $key,
975 'skipRecentView' => TRUE,
978 // we only handle related contact success, we ignore failures for now
979 // at some point wold be nice to have related counts as separate
981 'contact' => $primaryContactId,
984 list($valid, $invalid, $duplicate, $saved, $relationshipIds) = CRM_Contact_BAO_Relationship
::legacyCreateMultiple($relationParams, $relationIds);
986 if ($valid ||
$duplicate) {
987 $relationIds['contactTarget'] = $relContactId;
988 $action = ($duplicate) ? CRM_Core_Action
::UPDATE
: CRM_Core_Action
::ADD
;
989 CRM_Contact_BAO_Relationship
::relatedMemberships($primaryContactId, $relationParams, $relationIds, $action);
992 //handle current employer, CRM-3532
994 $allRelationships = CRM_Core_PseudoConstant
::relationshipType('name');
995 $relationshipTypeId = str_replace([
1002 $relationshipType = str_replace($relationshipTypeId . '_', '', $key);
1003 $orgId = $individualId = NULL;
1004 if ($allRelationships[$relationshipTypeId]["name_{$relationshipType}"] == 'Employee of') {
1005 $orgId = $relContactId;
1006 $individualId = $primaryContactId;
1008 elseif ($allRelationships[$relationshipTypeId]["name_{$relationshipType}"] == 'Employer of') {
1009 $orgId = $primaryContactId;
1010 $individualId = $relContactId;
1012 if ($orgId && $individualId) {
1013 $currentEmpParams[$individualId] = $orgId;
1014 CRM_Contact_BAO_Contact_Utils
::setCurrentEmployer($currentEmpParams);
1022 if ($this->_updateWithId
) {
1023 //return warning if street address is unparsed, CRM-5886
1024 return $this->processMessage($values, $statusFieldName, $this->_retCode
);
1027 if (is_array($newContact) && civicrm_error($newContact)) {
1030 if (($code = CRM_Utils_Array
::value('code', $newContact['error_message'])) && ($code == CRM_Core_Error
::DUPLICATE_CONTACT
)) {
1032 // need to fix at some stage and decide if the error will return an
1033 // array or string, crude hack for now
1034 if (is_array($newContact['error_message']['params'][0])) {
1035 $cids = $newContact['error_message']['params'][0];
1038 $cids = explode(',', $newContact['error_message']['params'][0]);
1041 foreach ($cids as $cid) {
1042 $urls[] = CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&cid=' . $cid, TRUE);
1045 $url_string = implode("\n", $urls);
1047 // If we duplicate more than one record, skip no matter what
1048 if (count($cids) > 1) {
1049 $errorMessage = ts('Record duplicates multiple contacts');
1050 $importRecordParams = [
1051 $statusFieldName => 'ERROR',
1052 "${statusFieldName}Msg" => $errorMessage,
1055 //combine error msg to avoid mismatch between error file columns.
1056 $errorMessage .= "\n" . $url_string;
1057 array_unshift($values, $errorMessage);
1058 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
1059 return CRM_Import_Parser
::ERROR
;
1062 // Params only had one id, so shift it out
1063 $contactId = array_shift($cids);
1066 $vals = ['contact_id' => $contactId];
1068 if ($onDuplicate == CRM_Import_Parser
::DUPLICATE_REPLACE
) {
1069 civicrm_api('contact', 'delete', $vals);
1070 $cid = CRM_Contact_BAO_Contact
::createProfileContact($formatted, $contactFields, $contactId, NULL, NULL, $formatted['contact_type']);
1072 elseif ($onDuplicate == CRM_Import_Parser
::DUPLICATE_UPDATE
) {
1073 $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactId);
1075 elseif ($onDuplicate == CRM_Import_Parser
::DUPLICATE_FILL
) {
1076 $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactId);
1078 // else skip does nothing and just returns an error code.
1081 'contact_id' => $cid,
1084 $newContact = CRM_Contact_BAO_Contact
::retrieve($contact, $defaults);
1087 if (civicrm_error($newContact)) {
1088 if (empty($newContact['error_message']['params'])) {
1089 // different kind of error other than DUPLICATE
1090 $errorMessage = $newContact['error_message'];
1091 array_unshift($values, $errorMessage);
1092 $importRecordParams = [
1093 $statusFieldName => 'ERROR',
1094 "${statusFieldName}Msg" => $errorMessage,
1096 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
1097 return CRM_Import_Parser
::ERROR
;
1100 $contactID = $newContact['error_message']['params'][0];
1101 if (is_array($contactID)) {
1102 $contactID = array_pop($contactID);
1104 if (!in_array($contactID, $this->_newContacts
)) {
1105 $this->_newContacts
[] = $contactID;
1108 //CRM-262 No Duplicate Checking
1109 if ($onDuplicate == CRM_Import_Parser
::DUPLICATE_SKIP
) {
1110 array_unshift($values, $url_string);
1111 $importRecordParams = [
1112 $statusFieldName => 'DUPLICATE',
1113 "${statusFieldName}Msg" => "Skipping duplicate record",
1115 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
1116 return CRM_Import_Parser
::DUPLICATE
;
1119 $importRecordParams = [
1120 $statusFieldName => 'IMPORTED',
1122 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
1123 //return warning if street address is not parsed, CRM-5886
1124 return $this->processMessage($values, $statusFieldName, CRM_Import_Parser
::VALID
);
1127 // Not a dupe, so we had an error
1128 $errorMessage = $newContact['error_message'];
1129 array_unshift($values, $errorMessage);
1130 $importRecordParams = [
1131 $statusFieldName => 'ERROR',
1132 "${statusFieldName}Msg" => $errorMessage,
1134 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
1135 return CRM_Import_Parser
::ERROR
;
1139 return $this->processMessage($values, $statusFieldName, CRM_Import_Parser
::VALID
);
1143 * Get the array of successfully imported contact id's
1147 public function &getImportedContacts() {
1148 return $this->_newContacts
;
1152 * Get the array of successfully imported related contact id's
1156 public function &getRelatedImportedContacts() {
1157 return $this->_newRelatedContacts
;
1161 * The initializer code, called before the processing.
1163 public function fini() {
1167 * Check if an error in custom data.
1169 * @param array $params
1170 * @param string $errorMessage
1171 * A string containing all the error-fields.
1173 * @param null $csType
1174 * @param null $relationships
1176 public static function isErrorInCustomData($params, &$errorMessage, $csType = NULL, $relationships = NULL) {
1177 $dateType = CRM_Core_Session
::singleton()->get("dateTypes");
1179 if (!empty($params['contact_sub_type'])) {
1180 $csType = CRM_Utils_Array
::value('contact_sub_type', $params);
1183 if (empty($params['contact_type'])) {
1184 $params['contact_type'] = 'Individual';
1187 // get array of subtypes - CRM-18708
1188 if (in_array($csType, ['Individual', 'Organization', 'Household'])) {
1189 $csType = self
::getSubtypes($params['contact_type']);
1192 if (is_array($csType)) {
1193 // fetch custom fields for every subtype and add it to $customFields array
1196 foreach ($csType as $cType) {
1197 $customFields +
= CRM_Core_BAO_CustomField
::getFields($params['contact_type'], FALSE, FALSE, $cType);
1201 $customFields = CRM_Core_BAO_CustomField
::getFields($params['contact_type'], FALSE, FALSE, $csType);
1204 $addressCustomFields = CRM_Core_BAO_CustomField
::getFields('Address');
1205 $customFields = $customFields +
$addressCustomFields;
1206 foreach ($params as $key => $value) {
1207 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($key)) {
1208 /* check if it's a valid custom field id */
1210 if (!array_key_exists($customFieldID, $customFields)) {
1211 self
::addToErrorMsg(ts('field ID'), $errorMessage);
1213 // validate null values for required custom fields of type boolean
1214 if (!empty($customFields[$customFieldID]['is_required']) && (empty($params['custom_' . $customFieldID]) && !is_numeric($params['custom_' . $customFieldID])) && $customFields[$customFieldID]['data_type'] == 'Boolean') {
1215 self
::addToErrorMsg($customFields[$customFieldID]['label'] . '::' . $customFields[$customFieldID]['groupTitle'], $errorMessage);
1218 //For address custom fields, we do get actual custom field value as an inner array of
1219 //values so need to modify
1220 if (array_key_exists($customFieldID, $addressCustomFields)) {
1221 $value = $value[0][$key];
1223 /* validate the data against the CF type */
1226 if ($customFields[$customFieldID]['data_type'] == 'Date') {
1227 if (array_key_exists($customFieldID, $addressCustomFields) && CRM_Utils_Date
::convertToDefaultDate($params[$key][0], $dateType, $key)) {
1228 $value = $params[$key][0][$key];
1230 elseif (CRM_Utils_Date
::convertToDefaultDate($params, $dateType, $key)) {
1231 $value = $params[$key];
1234 self
::addToErrorMsg($customFields[$customFieldID]['label'], $errorMessage);
1237 elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
1238 if (CRM_Utils_String
::strtoboolstr($value) === FALSE) {
1239 self
::addToErrorMsg($customFields[$customFieldID]['label'] . '::' . $customFields[$customFieldID]['groupTitle'], $errorMessage);
1242 // need not check for label filed import
1248 'Multi-Select State/Province',
1249 'Multi-Select Country',
1251 if (!in_array($customFields[$customFieldID]['html_type'], $htmlType) ||
$customFields[$customFieldID]['data_type'] == 'Boolean' ||
$customFields[$customFieldID]['data_type'] == 'ContactReference') {
1252 $valid = CRM_Core_BAO_CustomValue
::typecheck($customFields[$customFieldID]['data_type'], $value);
1254 self
::addToErrorMsg($customFields[$customFieldID]['label'], $errorMessage);
1258 // check for values for custom fields for checkboxes and multiselect
1259 if ($customFields[$customFieldID]['html_type'] == 'CheckBox' ||
$customFields[$customFieldID]['html_type'] == 'Multi-Select') {
1260 $value = trim($value);
1261 $value = str_replace('|', ',', $value);
1262 $mulValues = explode(',', $value);
1263 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldID, TRUE);
1264 foreach ($mulValues as $v1) {
1265 if (strlen($v1) == 0) {
1270 foreach ($customOption as $v2) {
1271 if ((strtolower(trim($v2['label'])) == strtolower(trim($v1))) ||
(strtolower(trim($v2['value'])) == strtolower(trim($v1)))) {
1277 self
::addToErrorMsg($customFields[$customFieldID]['label'], $errorMessage);
1281 elseif ($customFields[$customFieldID]['html_type'] == 'Select' ||
($customFields[$customFieldID]['html_type'] == 'Radio' && $customFields[$customFieldID]['data_type'] != 'Boolean')) {
1282 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldID, TRUE);
1284 foreach ($customOption as $v2) {
1285 if ((strtolower(trim($v2['label'])) == strtolower(trim($value))) ||
(strtolower(trim($v2['value'])) == strtolower(trim($value)))) {
1290 self
::addToErrorMsg($customFields[$customFieldID]['label'], $errorMessage);
1293 elseif ($customFields[$customFieldID]['html_type'] == 'Multi-Select State/Province') {
1294 $mulValues = explode(',', $value);
1295 foreach ($mulValues as $stateValue) {
1297 if (self
::in_value(trim($stateValue), CRM_Core_PseudoConstant
::stateProvinceAbbreviation()) || self
::in_value(trim($stateValue), CRM_Core_PseudoConstant
::stateProvince())) {
1301 self
::addToErrorMsg($customFields[$customFieldID]['label'], $errorMessage);
1306 elseif ($customFields[$customFieldID]['html_type'] == 'Multi-Select Country') {
1307 $mulValues = explode(',', $value);
1308 foreach ($mulValues as $countryValue) {
1309 if ($countryValue) {
1310 CRM_Core_PseudoConstant
::populate($countryNames, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active');
1311 CRM_Core_PseudoConstant
::populate($countryIsoCodes, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
1312 $limitCodes = CRM_Core_BAO_Country
::countryLimit();
1320 if (in_array(trim($countryValue), $values)) {
1327 self
::addToErrorMsg($customFields[$customFieldID]['label'], $errorMessage);
1334 elseif (is_array($params[$key]) && isset($params[$key]["contact_type"])) {
1336 //supporting custom data of related contact subtypes
1338 if ($relationships) {
1339 if (array_key_exists($key, $relationships)) {
1342 elseif (CRM_Utils_Array
::key($key, $relationships)) {
1343 $relation = CRM_Utils_Array
::key($key, $relationships);
1346 if (!empty($relation)) {
1347 list($id, $first, $second) = CRM_Utils_System
::explode('_', $relation, 3);
1348 $direction = "contact_sub_type_$second";
1349 $relationshipType = new CRM_Contact_BAO_RelationshipType();
1350 $relationshipType->id
= $id;
1351 if ($relationshipType->find(TRUE)) {
1352 if (isset($relationshipType->$direction)) {
1353 $params[$key]['contact_sub_type'] = $relationshipType->$direction;
1356 $relationshipType->free();
1359 self
::isErrorInCustomData($params[$key], $errorMessage, $csType, $relationships);
1365 * Check if value present in all genders or.
1366 * as a substring of any gender value, if yes than return corresponding gender.
1367 * eg value might be m/M, ma/MA, mal/MAL, male return 'Male'
1368 * but if value is 'maleabc' than return false
1370 * @param string $gender
1371 * Check this value across gender values.
1373 * retunr gender value / false
1377 public function checkGender($gender) {
1378 $gender = trim($gender, '.');
1383 $allGenders = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id');
1384 foreach ($allGenders as $key => $value) {
1385 if (strlen($gender) > strlen($value)) {
1388 if ($gender == $value) {
1391 if (substr_compare($value, $gender, 0, strlen($gender), TRUE) === 0) {
1400 * Check if an error in Core( non-custom fields ) field
1402 * @param array $params
1403 * @param string $errorMessage
1404 * A string containing all the error-fields.
1406 public function isErrorInCoreData($params, &$errorMessage) {
1407 foreach ($params as $key => $value) {
1409 $session = CRM_Core_Session
::singleton();
1410 $dateType = $session->get("dateTypes");
1414 if (CRM_Utils_Date
::convertToDefaultDate($params, $dateType, $key)) {
1415 if (!CRM_Utils_Rule
::date($params[$key])) {
1416 self
::addToErrorMsg(ts('Birth Date'), $errorMessage);
1420 self
::addToErrorMsg(ts('Birth-Date'), $errorMessage);
1424 case 'deceased_date':
1425 if (CRM_Utils_Date
::convertToDefaultDate($params, $dateType, $key)) {
1426 if (!CRM_Utils_Rule
::date($params[$key])) {
1427 self
::addToErrorMsg(ts('Deceased Date'), $errorMessage);
1431 self
::addToErrorMsg(ts('Deceased Date'), $errorMessage);
1436 if (CRM_Utils_String
::strtoboolstr($value) === FALSE) {
1437 self
::addToErrorMsg(ts('Deceased'), $errorMessage);
1443 if (!self
::checkGender($value)) {
1444 self
::addToErrorMsg(ts('Gender'), $errorMessage);
1448 case 'preferred_communication_method':
1450 $preffComm = explode(',', $value);
1451 foreach ($preffComm as $v) {
1452 if (!self
::in_value(trim($v), CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method'))) {
1453 self
::addToErrorMsg(ts('Preferred Communication Method'), $errorMessage);
1458 case 'preferred_mail_format':
1459 if (!array_key_exists(strtolower($value), array_change_key_case(CRM_Core_SelectValues
::pmf(), CASE_LOWER
))) {
1460 self
::addToErrorMsg(ts('Preferred Mail Format'), $errorMessage);
1464 case 'individual_prefix':
1466 if (!self
::in_value($value, CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'))) {
1467 self
::addToErrorMsg(ts('Individual Prefix'), $errorMessage);
1471 case 'individual_suffix':
1473 if (!self
::in_value($value, CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'))) {
1474 self
::addToErrorMsg(ts('Individual Suffix'), $errorMessage);
1478 case 'state_province':
1479 if (!empty($value)) {
1480 foreach ($value as $stateValue) {
1481 if ($stateValue['state_province']) {
1482 if (self
::in_value($stateValue['state_province'], CRM_Core_PseudoConstant
::stateProvinceAbbreviation()) ||
1483 self
::in_value($stateValue['state_province'], CRM_Core_PseudoConstant
::stateProvince())
1488 self
::addToErrorMsg(ts('State/Province'), $errorMessage);
1496 if (!empty($value)) {
1497 foreach ($value as $stateValue) {
1498 if ($stateValue['country']) {
1499 CRM_Core_PseudoConstant
::populate($countryNames, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active');
1500 CRM_Core_PseudoConstant
::populate($countryIsoCodes, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
1501 $limitCodes = CRM_Core_BAO_Country
::countryLimit();
1502 //If no country is selected in
1503 //localization then take all countries
1504 if (empty($limitCodes)) {
1505 $limitCodes = $countryIsoCodes;
1508 if (self
::in_value($stateValue['country'], $limitCodes) || self
::in_value($stateValue['country'], CRM_Core_PseudoConstant
::country())) {
1512 if (self
::in_value($stateValue['country'], $countryIsoCodes) || self
::in_value($stateValue['country'], $countryNames)) {
1513 self
::addToErrorMsg(ts('Country input value is in table but not "available": "This Country is valid but is NOT in the list of Available Countries currently configured for your site. This can be viewed and modifed from Administer > Localization > Languages Currency Locations." '), $errorMessage);
1516 self
::addToErrorMsg(ts('Country input value not in country table: "The Country value appears to be invalid. It does not match any value in CiviCRM table of countries."'), $errorMessage);
1525 if (!empty($value)) {
1526 foreach ($value as $county) {
1527 if ($county['county']) {
1528 $countyNames = CRM_Core_PseudoConstant
::county();
1529 if (!empty($county['county']) && !in_array($county['county'], $countyNames)) {
1530 self
::addToErrorMsg(ts('County input value not in county table: The County value appears to be invalid. It does not match any value in CiviCRM table of counties.'), $errorMessage);
1538 if (!empty($value)) {
1539 foreach ($value as $codeValue) {
1540 if (!empty($codeValue['geo_code_1'])) {
1541 if (CRM_Utils_Rule
::numeric($codeValue['geo_code_1'])) {
1545 self
::addToErrorMsg(ts('Geo code 1'), $errorMessage);
1553 if (!empty($value)) {
1554 foreach ($value as $codeValue) {
1555 if (!empty($codeValue['geo_code_2'])) {
1556 if (CRM_Utils_Rule
::numeric($codeValue['geo_code_2'])) {
1560 self
::addToErrorMsg(ts('Geo code 2'), $errorMessage);
1567 //check for any error in email/postal greeting, addressee,
1568 //custom email/postal greeting, custom addressee, CRM-4575
1570 case 'email_greeting':
1571 $emailGreetingFilter = [
1572 'contact_type' => $this->_contactType
,
1573 'greeting_type' => 'email_greeting',
1575 if (!self
::in_value($value, CRM_Core_PseudoConstant
::greeting($emailGreetingFilter))) {
1576 self
::addToErrorMsg(ts('Email Greeting must be one of the configured format options. Check Administer >> System Settings >> Option Groups >> Email Greetings for valid values'), $errorMessage);
1580 case 'postal_greeting':
1581 $postalGreetingFilter = [
1582 'contact_type' => $this->_contactType
,
1583 'greeting_type' => 'postal_greeting',
1585 if (!self
::in_value($value, CRM_Core_PseudoConstant
::greeting($postalGreetingFilter))) {
1586 self
::addToErrorMsg(ts('Postal Greeting must be one of the configured format options. Check Administer >> System Settings >> Option Groups >> Postal Greetings for valid values'), $errorMessage);
1591 $addresseeFilter = [
1592 'contact_type' => $this->_contactType
,
1593 'greeting_type' => 'addressee',
1595 if (!self
::in_value($value, CRM_Core_PseudoConstant
::greeting($addresseeFilter))) {
1596 self
::addToErrorMsg(ts('Addressee must be one of the configured format options. Check Administer >> System Settings >> Option Groups >> Addressee for valid values'), $errorMessage);
1600 case 'email_greeting_custom':
1601 if (array_key_exists('email_greeting', $params)) {
1602 $emailGreetingLabel = key(CRM_Core_OptionGroup
::values('email_greeting', TRUE, NULL, NULL, 'AND v.name = "Customized"'));
1603 if (CRM_Utils_Array
::value('email_greeting', $params) != $emailGreetingLabel) {
1604 self
::addToErrorMsg(ts('Email Greeting - Custom'), $errorMessage);
1609 case 'postal_greeting_custom':
1610 if (array_key_exists('postal_greeting', $params)) {
1611 $postalGreetingLabel = key(CRM_Core_OptionGroup
::values('postal_greeting', TRUE, NULL, NULL, 'AND v.name = "Customized"'));
1612 if (CRM_Utils_Array
::value('postal_greeting', $params) != $postalGreetingLabel) {
1613 self
::addToErrorMsg(ts('Postal Greeting - Custom'), $errorMessage);
1618 case 'addressee_custom':
1619 if (array_key_exists('addressee', $params)) {
1620 $addresseeLabel = key(CRM_Core_OptionGroup
::values('addressee', TRUE, NULL, NULL, 'AND v.name = "Customized"'));
1621 if (CRM_Utils_Array
::value('addressee', $params) != $addresseeLabel) {
1622 self
::addToErrorMsg(ts('Addressee - Custom'), $errorMessage);
1628 if (is_array($value)) {
1629 foreach ($value as $values) {
1630 if (!empty($values['url']) && !CRM_Utils_Rule
::url($values['url'])) {
1631 self
::addToErrorMsg(ts('Website'), $errorMessage);
1638 case 'do_not_email':
1639 case 'do_not_phone':
1642 case 'do_not_trade':
1643 if (CRM_Utils_Rule
::boolean($value) == FALSE) {
1644 $key = ucwords(str_replace("_", " ", $key));
1645 self
::addToErrorMsg($key, $errorMessage);
1650 if (is_array($value)) {
1651 foreach ($value as $values) {
1652 if (!empty($values['email']) && !CRM_Utils_Rule
::email($values['email'])) {
1653 self
::addToErrorMsg($key, $errorMessage);
1661 if (is_array($params[$key]) && isset($params[$key]["contact_type"])) {
1662 //check for any relationship data ,FIX ME
1663 self
::isErrorInCoreData($params[$key], $errorMessage);
1671 * Ckeck a value present or not in a array.
1674 * @param $valueArray
1678 public static function in_value($value, $valueArray) {
1679 foreach ($valueArray as $key => $v) {
1681 if (strtolower(trim($v, ".")) == strtolower(trim($value, "."))) {
1689 * Build error-message containing error-fields
1691 * Once upon a time there was a dev who hadn't heard of implode. That dev wrote this function.
1693 * @todo just say no!
1695 * @param string $errorName
1696 * A string containing error-field name.
1697 * @param string $errorMessage
1698 * A string containing all the error-fields, where the new errorName is concatenated.
1701 public static function addToErrorMsg($errorName, &$errorMessage) {
1702 if ($errorMessage) {
1703 $errorMessage .= "; $errorName";
1706 $errorMessage = $errorName;
1711 * Method for creating contact.
1713 * @param array $formatted
1714 * @param array $contactFields
1715 * @param int $onDuplicate
1716 * @param int $contactId
1717 * @param bool $requiredCheck
1718 * @param int $dedupeRuleGroupID
1720 * @return array|bool|\CRM_Contact_BAO_Contact|\CRM_Core_Error|null
1722 public function createContact(&$formatted, &$contactFields, $onDuplicate, $contactId = NULL, $requiredCheck = TRUE, $dedupeRuleGroupID = NULL) {
1726 if (is_null($contactId) && ($onDuplicate != CRM_Import_Parser
::DUPLICATE_NOCHECK
)) {
1727 $dupeCheck = (bool) ($onDuplicate);
1730 //get the prefix id etc if exists
1731 CRM_Contact_BAO_Contact
::resolveDefaults($formatted, TRUE);
1733 //@todo direct call to API function not supported.
1734 // setting required check to false, CRM-2839
1735 // plus we do our own required check in import
1736 $error = _civicrm_api3_deprecated_contact_check_params($formatted, $dupeCheck, $dedupeRuleGroupID);
1738 if ((is_null($error)) && (civicrm_error(_civicrm_api3_deprecated_validate_formatted_contact($formatted)))) {
1739 $error = _civicrm_api3_deprecated_validate_formatted_contact($formatted);
1742 $newContact = $error;
1744 if (is_null($error)) {
1746 $this->formatParams($formatted, $onDuplicate, (int) $contactId);
1749 // Resetting and rebuilding cache could be expensive.
1750 CRM_Core_Config
::setPermitCacheFlushMode(FALSE);
1751 $cid = CRM_Contact_BAO_Contact
::createProfileContact($formatted, $contactFields, $contactId, NULL, NULL, $formatted['contact_type']);
1752 CRM_Core_Config
::setPermitCacheFlushMode(TRUE);
1755 'contact_id' => $cid,
1759 $newContact = CRM_Contact_BAO_Contact
::retrieve($contact, $defaults);
1762 //get the id of the contact whose street address is not parsable, CRM-5886
1763 if ($this->_parseStreetAddress
&& is_object($newContact) && property_exists($newContact, 'address') && $newContact->address
) {
1764 foreach ($newContact->address
as $address) {
1765 if (!empty($address['street_address']) && (empty($address['street_number']) ||
empty($address['street_name']))) {
1766 $this->_unparsedStreetAddressContacts
[] = [
1767 'id' => $newContact->id
,
1768 'streetAddress' => $address['street_address'],
1777 * Format params for update and fill mode.
1779 * @param array $params
1780 * reference to an array containing all the.
1782 * @param int $onDuplicate
1786 public function formatParams(&$params, $onDuplicate, $cid) {
1787 if ($onDuplicate == CRM_Import_Parser
::DUPLICATE_SKIP
) {
1792 'contact_id' => $cid,
1796 $contactObj = CRM_Contact_BAO_Contact
::retrieve($contactParams, $defaults);
1798 $modeUpdate = $modeFill = FALSE;
1800 if ($onDuplicate == CRM_Import_Parser
::DUPLICATE_UPDATE
) {
1804 if ($onDuplicate == CRM_Import_Parser
::DUPLICATE_FILL
) {
1808 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($params['contact_type'], NULL, $cid, 0, NULL);
1809 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $defaults, FALSE, FALSE);
1815 'website' => 'website',
1816 'address' => 'address',
1819 $contact = get_object_vars($contactObj);
1821 foreach ($params as $key => $value) {
1822 if ($key == 'id' ||
$key == 'contact_type') {
1826 if (array_key_exists($key, $locationFields)) {
1829 elseif (in_array($key, [
1834 // CRM-4575, need to null custom
1835 if ($params["{$key}_id"] != 4) {
1836 $params["{$key}_custom"] = 'null';
1838 unset($params[$key]);
1841 if ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key)) {
1842 $custom_params = ['id' => $contact['id'], 'return' => $key];
1843 $getValue = civicrm_api3('Contact', 'getvalue', $custom_params);
1844 if (empty($getValue)) {
1849 $getValue = CRM_Utils_Array
::retrieveValueRecursive($contact, $key);
1851 if ($key == 'contact_source') {
1852 $params['source'] = $params[$key];
1853 unset($params[$key]);
1856 if ($modeFill && isset($getValue)) {
1857 unset($params[$key]);
1858 if ($customFieldId) {
1859 // Extra values must be unset to ensure the values are not
1861 unset($params['custom'][$customFieldId]);
1867 foreach ($locationFields as $locKeys) {
1868 if (is_array(CRM_Utils_Array
::value($locKeys, $params))) {
1869 foreach ($params[$locKeys] as $key => $value) {
1871 $getValue = CRM_Utils_Array
::retrieveValueRecursive($contact, $locKeys);
1873 if (isset($getValue)) {
1874 foreach ($getValue as $cnt => $values) {
1875 if ($locKeys == 'website') {
1876 if (($getValue[$cnt]['website_type_id'] == $params[$locKeys][$key]['website_type_id'])) {
1877 unset($params[$locKeys][$key]);
1881 if ((!empty($getValue[$cnt]['location_type_id']) && !empty($params[$locKeys][$key]['location_type_id'])) && $getValue[$cnt]['location_type_id'] == $params[$locKeys][$key]['location_type_id']) {
1882 unset($params[$locKeys][$key]);
1889 if (count($params[$locKeys]) == 0) {
1890 unset($params[$locKeys]);
1897 * Convert any given date string to default date array.
1899 * @param array $params
1900 * Has given date-format.
1901 * @param array $formatted
1902 * Store formatted date in this array.
1903 * @param int $dateType
1905 * @param string $dateParam
1908 public static function formatCustomDate(&$params, &$formatted, $dateType, $dateParam) {
1910 CRM_Utils_Date
::convertToDefaultDate($params, $dateType, $dateParam);
1911 $formatted[$dateParam] = CRM_Utils_Date
::processDate($params[$dateParam]);
1915 * Generate status and error message for unparsed street address records.
1917 * @param array $values
1918 * The array of values belonging to each row.
1919 * @param array $statusFieldName
1920 * Store formatted date in this array.
1921 * @param $returnCode
1925 public function processMessage(&$values, $statusFieldName, $returnCode) {
1926 if (empty($this->_unparsedStreetAddressContacts
)) {
1927 $importRecordParams = [
1928 $statusFieldName => 'IMPORTED',
1932 $errorMessage = ts("Record imported successfully but unable to parse the street address: ");
1933 foreach ($this->_unparsedStreetAddressContacts
as $contactInfo => $contactValue) {
1934 $contactUrl = CRM_Utils_System
::url('civicrm/contact/add', 'reset=1&action=update&cid=' . $contactValue['id'], TRUE, NULL, FALSE);
1935 $errorMessage .= "\n Contact ID:" . $contactValue['id'] . " <a href=\"$contactUrl\"> " . $contactValue['streetAddress'] . "</a>";
1937 array_unshift($values, $errorMessage);
1938 $importRecordParams = [
1939 $statusFieldName => 'ERROR',
1940 "${statusFieldName}Msg" => $errorMessage,
1942 $returnCode = CRM_Import_Parser
::UNPARSED_ADDRESS_WARNING
;
1944 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
1950 * @param array $params
1954 public function checkRelatedContactFields($relKey, $params) {
1955 //avoid blank contact creation.
1956 $allowToCreate = FALSE;
1958 //build the mapper field array.
1959 static $relatedContactFields = [];
1960 if (!isset($relatedContactFields[$relKey])) {
1961 foreach ($this->_mapperRelated
as $key => $name) {
1966 if (!empty($relatedContactFields[$name]) && !is_array($relatedContactFields[$name])) {
1967 $relatedContactFields[$name] = [];
1969 $fldName = CRM_Utils_Array
::value($key, $this->_mapperRelatedContactDetails
);
1970 if ($fldName == 'url') {
1971 $fldName = 'website';
1974 $relatedContactFields[$name][] = $fldName;
1979 //validate for passed data.
1980 if (is_array($relatedContactFields[$relKey])) {
1981 foreach ($relatedContactFields[$relKey] as $fld) {
1982 if (!empty($params[$fld])) {
1983 $allowToCreate = TRUE;
1989 return $allowToCreate;
1993 * get subtypes given the contact type
1995 * @param string $contactType
1996 * @return array $subTypes
1998 public static function getSubtypes($contactType) {
2000 $types = CRM_Contact_BAO_ContactType
::subTypeInfo($contactType);
2002 if (count($types) > 0) {
2003 foreach ($types as $type) {
2004 $subTypes[] = $type['name'];
2011 * Get the possible contact matches.
2013 * 1) the chosen dedupe rule falling back to
2014 * 2) a check for the external ID.
2018 * @param array $params
2021 * IDs of possible matches.
2023 * @throws \CRM_Core_Exception
2024 * @throws \CiviCRM_API3_Exception
2026 protected function getPossibleContactMatches($params) {
2029 if (!empty($params['external_identifier'])) {
2030 // Check for any match on external id, deleted or otherwise.
2031 $extIDContact = civicrm_api3('Contact', 'get', [
2032 'external_identifier' => $params['external_identifier'],
2034 'return' => ['id', 'contact_is_deleted'],
2036 if (isset($extIDContact['id'])) {
2037 $extIDMatch = $extIDContact['id'];
2039 if ($extIDContact['values'][$extIDMatch]['contact_is_deleted'] == 1) {
2040 // If the contact is deleted, update external identifier to be blank
2041 // to avoid key error from MySQL.
2042 $params = ['id' => $extIDMatch, 'external_identifier' => ''];
2043 civicrm_api3('Contact', 'create', $params);
2045 // And now it is no longer a match.
2050 $checkParams = ['check_permissions' => FALSE, 'match' => $params];
2051 $checkParams['match']['contact_type'] = $this->_contactType
;
2053 $possibleMatches = civicrm_api3('Contact', 'duplicatecheck', $checkParams);
2055 return array_keys($possibleMatches['values']);
2057 if ($possibleMatches['count']) {
2058 if (in_array($extIDMatch, array_keys($possibleMatches['values']))) {
2059 return [$extIDMatch];
2062 throw new CRM_Core_Exception(ts(
2063 'Matching this contact based on the de-dupe rule would cause an external ID conflict'));
2066 return [$extIDMatch];
2070 * Format the form mapping parameters ready for the parser.
2075 * @return array $parserParameters
2077 public static function getParameterForParser($count) {
2079 for ($i = 0; $i < $count; $i++
) {
2080 $baseArray[$i] = NULL;
2082 $parserParameters['mapperLocType'] = $baseArray;
2083 $parserParameters['mapperPhoneType'] = $baseArray;
2084 $parserParameters['mapperImProvider'] = $baseArray;
2085 $parserParameters['mapperWebsiteType'] = $baseArray;
2086 $parserParameters['mapperRelated'] = $baseArray;
2087 $parserParameters['relatedContactType'] = $baseArray;
2088 $parserParameters['relatedContactDetails'] = $baseArray;
2089 $parserParameters['relatedContactLocType'] = $baseArray;
2090 $parserParameters['relatedContactPhoneType'] = $baseArray;
2091 $parserParameters['relatedContactImProvider'] = $baseArray;
2092 $parserParameters['relatedContactWebsiteType'] = $baseArray;
2094 return $parserParameters;