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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * This class gets the name of the file to upload.
37 class CRM_Contact_Import_Form_MapField
extends CRM_Import_Form_MapField
{
39 use CRM_Contact_Import_MetadataTrait
;
42 * An array of all contact fields with
43 * formatted custom field names.
47 protected $_formattedFieldNames;
56 protected $_dedupeFields;
58 protected static $customFields;
61 * Attempt to match header labels with our mapper fields.
63 * FIXME: This is essentially the same function as parent::defaultFromHeader
65 * @param string $columnName name of column header
66 * @param array $patterns pattern to match for the column
70 public function defaultFromColumnName($columnName, $patterns) {
72 if (!preg_match('/^[a-z0-9 ]$/i', $columnName)) {
73 if ($columnKey = array_search($columnName, $this->_mapperFields
)) {
74 $this->_fieldUsed
[$columnKey] = TRUE;
79 foreach ($patterns as $key => $re) {
80 // Skip empty key/patterns
81 if (!$key ||
!$re ||
strlen("$re") < 5) {
85 if (preg_match($re, $columnName)) {
86 $this->_fieldUsed
[$key] = TRUE;
94 * Set variables up before form is built.
96 public function preProcess() {
97 $dataSource = $this->get('dataSource');
98 $skipColumnHeader = $this->get('skipColumnHeader');
99 $this->_mapperFields
= $this->get('fields');
100 $this->_importTableName
= $this->get('importTableName');
101 $this->_onDuplicate
= $this->get('onDuplicate');
102 $highlightedFields = [];
103 $highlightedFields[] = 'email';
104 $highlightedFields[] = 'external_identifier';
105 //format custom field names, CRM-2676
106 switch ($this->get('contactType')) {
107 case CRM_Import_Parser
::CONTACT_INDIVIDUAL
:
108 $contactType = 'Individual';
109 $highlightedFields[] = 'first_name';
110 $highlightedFields[] = 'last_name';
113 case CRM_Import_Parser
::CONTACT_HOUSEHOLD
:
114 $contactType = 'Household';
115 $highlightedFields[] = 'household_name';
118 case CRM_Import_Parser
::CONTACT_ORGANIZATION
:
119 $contactType = 'Organization';
120 $highlightedFields[] = 'organization_name';
123 $this->_contactType
= $contactType;
124 if ($this->_onDuplicate
== CRM_Import_Parser
::DUPLICATE_SKIP
) {
125 unset($this->_mapperFields
['id']);
128 $highlightedFields[] = 'id';
131 if ($this->_onDuplicate
!= CRM_Import_Parser
::DUPLICATE_NOCHECK
) {
132 //Mark Dedupe Rule Fields as required, since it's used in matching contact
133 foreach (['Individual', 'Household', 'Organization'] as $cType) {
135 'contact_type' => $cType,
136 'used' => 'Unsupervised',
138 $this->_dedupeFields
[$cType] = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
141 //Modify mapper fields title if fields are present in dedupe rule
142 if (is_array($this->_dedupeFields
[$contactType])) {
143 foreach ($this->_dedupeFields
[$contactType] as $val) {
144 if ($valTitle = CRM_Utils_Array
::value($val, $this->_mapperFields
)) {
145 $this->_mapperFields
[$val] = $valTitle . ' (match to contact)';
150 // retrieve and highlight required custom fields
151 $formattedFieldNames = $this->formatCustomFieldName($this->_mapperFields
);
152 self
::$customFields = CRM_Core_BAO_CustomField
::getFields($this->_contactType
);
153 foreach (self
::$customFields as $key => $attr) {
154 if (!empty($attr['is_required'])) {
155 $highlightedFields[] = "custom_$key";
158 $this->assign('highlightedFields', $highlightedFields);
159 $this->_formattedFieldNames
[$contactType] = $this->_mapperFields
= array_merge($this->_mapperFields
, $formattedFieldNames);
162 //get original col headers from csv if present.
163 if ($dataSource == 'CRM_Import_DataSource_CSV' && $skipColumnHeader) {
164 $columnNames = $this->get('originalColHeader');
167 // get the field names from the temp. DB table
168 $dao = new CRM_Core_DAO();
169 $db = $dao->getDatabaseConnection();
171 $columnsQuery = "SHOW FIELDS FROM $this->_importTableName
172 WHERE Field NOT LIKE '\_%'";
173 $columnsResult = $db->query($columnsQuery);
174 while ($row = $columnsResult->fetchRow(DB_FETCHMODE_ASSOC
)) {
175 $columnNames[] = $row['Field'];
179 $showColNames = TRUE;
180 if ($dataSource === 'CRM_Import_DataSource_CSV' && !$skipColumnHeader) {
181 $showColNames = FALSE;
183 $this->assign('showColNames', $showColNames);
185 $this->_columnCount
= count($columnNames);
186 $this->_columnNames
= $columnNames;
187 $this->assign('columnNames', $columnNames);
188 //$this->_columnCount = $this->get( 'columnCount' );
189 $this->assign('columnCount', $this->_columnCount
);
190 $this->_dataValues
= $this->get('dataValues');
191 $this->assign('dataValues', $this->_dataValues
);
192 $this->assign('rowDisplayCount', 2);
196 * Build the form object.
198 * @throws \CiviCRM_API3_Exception
200 public function buildQuickForm() {
201 $savedMappingID = (int) $this->get('savedMapping');
202 //to save the current mappings
203 if (!$savedMappingID) {
204 $saveDetailsName = ts('Save this field mapping');
205 $this->applyFilter('saveMappingName', 'trim');
206 $this->add('text', 'saveMappingName', ts('Name'));
207 $this->add('text', 'saveMappingDesc', ts('Description'));
210 $savedMapping = $this->get('savedMapping');
212 list($mappingName) = CRM_Core_BAO_Mapping
::getMappingFields($savedMapping, TRUE);
214 //get loaded Mapping Fields
215 $mappingName = CRM_Utils_Array
::value(1, $mappingName);
217 $this->assign('loadedMapping', $savedMapping);
218 $this->set('loadedMapping', $savedMapping);
220 $params = ['id' => $savedMapping];
222 $mappingDetails = CRM_Core_BAO_Mapping
::retrieve($params, $temp);
224 $this->assign('savedName', $mappingDetails->name
);
226 $this->add('hidden', 'mappingId', $savedMapping);
228 $this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
229 $saveDetailsName = ts('Save as a new field mapping');
230 $this->add('text', 'saveMappingName', ts('Name'));
231 $this->add('text', 'saveMappingDesc', ts('Description'));
234 $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, ['onclick' => "showSaveDetails(this)"]);
236 $this->addFormRule(['CRM_Contact_Import_Form_MapField', 'formRule']);
238 //-------- end of saved mapping stuff ---------
241 $mapperKeys = array_keys($this->_mapperFields
);
242 $hasColumnNames = !empty($this->_columnNames
);
243 $columnPatterns = $this->get('columnPatterns');
244 $dataPatterns = $this->get('dataPatterns');
245 $hasLocationTypes = $this->get('fieldTypes');
247 $this->_location_types
= ['Primary' => ts('Primary')] + CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
248 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
250 // Pass default location to js
251 if ($defaultLocationType) {
252 $this->assign('defaultLocationType', $defaultLocationType->id
);
253 $this->assign('defaultLocationTypeLabel', $this->_location_types
[$defaultLocationType->id
]);
256 /* Initialize all field usages to false */
257 foreach ($mapperKeys as $key) {
258 $this->_fieldUsed
[$key] = FALSE;
261 $sel1 = $this->_mapperFields
;
264 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
265 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
266 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
268 foreach ($this->_location_types
as $key => $value) {
269 $sel3['phone'][$key] = &$phoneTypes;
270 //build array for IM service provider type for contact
271 $sel3['im'][$key] = &$imProviders;
276 // store and cache all relationship types
277 $contactRelation = new CRM_Contact_DAO_RelationshipType();
278 $contactRelation->find();
279 while ($contactRelation->fetch()) {
280 $contactRelationCache[$contactRelation->id
] = [];
281 $contactRelationCache[$contactRelation->id
]['contact_type_a'] = $contactRelation->contact_type_a
;
282 $contactRelationCache[$contactRelation->id
]['contact_sub_type_a'] = $contactRelation->contact_sub_type_a
;
283 $contactRelationCache[$contactRelation->id
]['contact_type_b'] = $contactRelation->contact_type_b
;
284 $contactRelationCache[$contactRelation->id
]['contact_sub_type_b'] = $contactRelation->contact_sub_type_b
;
286 $highlightedFields = $highlightedRelFields = [];
288 $highlightedFields['email'] = 'All';
289 $highlightedFields['external_identifier'] = 'All';
290 $highlightedFields['first_name'] = 'Individual';
291 $highlightedFields['last_name'] = 'Individual';
292 $highlightedFields['household_name'] = 'Household';
293 $highlightedFields['organization_name'] = 'Organization';
295 foreach ($mapperKeys as $key) {
296 // check if there is a _a_b or _b_a in the key
297 if (strpos($key, '_a_b') ||
strpos($key, '_b_a')) {
298 list($id, $first, $second) = explode('_', $key);
301 $id = $first = $second = NULL;
303 if (($first === 'a' && $second === 'b') ||
($first === 'b' && $second === 'a')) {
304 $cType = $contactRelationCache[$id]["contact_type_{$second}"];
306 //CRM-5125 for contact subtype specific relationshiptypes
308 if (!empty($contactRelationCache[$id]["contact_sub_type_{$second}"])) {
309 $cSubType = $contactRelationCache[$id]["contact_sub_type_{$second}"];
316 $relatedFields = CRM_Contact_BAO_Contact
::importableFields($cType);
317 unset($relatedFields['']);
319 foreach ($relatedFields as $name => $field) {
320 $values[$name] = $field['title'];
321 if (isset($hasLocationTypes[$name])) {
322 $sel3[$key][$name] = $this->_location_types
;
324 elseif ($name === 'url') {
325 $sel3[$key][$name] = $websiteTypes;
332 //fix to append custom group name to field name, CRM-2676
333 if (empty($this->_formattedFieldNames
[$cType]) ||
$cType == $this->_contactType
) {
334 $this->_formattedFieldNames
[$cType] = $this->formatCustomFieldName($values);
337 $this->_formattedFieldNames
[$cType] = array_merge($values, $this->_formattedFieldNames
[$cType]);
339 //Modified the Relationship fields if the fields are
340 //present in dedupe rule
341 if ($this->_onDuplicate
!= CRM_Import_Parser
::DUPLICATE_NOCHECK
&& !empty($this->_dedupeFields
[$cType]) &&
342 is_array($this->_dedupeFields
[$cType])
344 static $cTypeArray = [];
345 if ($cType != $this->_contactType
&& !in_array($cType, $cTypeArray)) {
346 foreach ($this->_dedupeFields
[$cType] as $val) {
347 if ($valTitle = CRM_Utils_Array
::value($val, $this->_formattedFieldNames
[$cType])) {
348 $this->_formattedFieldNames
[$cType][$val] = $valTitle . ' (match to contact)';
351 $cTypeArray[] = $cType;
355 foreach ($highlightedFields as $k => $v) {
356 if ($v == $cType ||
$v === 'All') {
357 $highlightedRelFields[$key][] = $k;
360 $this->assign('highlightedRelFields', $highlightedRelFields);
361 $sel2[$key] = $this->_formattedFieldNames
[$cType];
363 if (!empty($cSubType)) {
364 //custom fields for sub type
365 $subTypeFields = CRM_Core_BAO_CustomField
::getFieldsForImport($cSubType);
367 if (!empty($subTypeFields)) {
369 foreach ($subTypeFields as $customSubTypeField => $details) {
370 $subType[$customSubTypeField] = $details['title'];
371 $sel2[$key] = array_merge($sel2[$key], $this->formatCustomFieldName($subType));
376 foreach ($this->_location_types
as $k => $value) {
377 $sel4[$key]['phone'][$k] = &$phoneTypes;
378 //build array of IM service provider for related contact
379 $sel4[$key]['im'][$k] = &$imProviders;
384 if (!empty($hasLocationTypes[$key])) {
385 $options = $this->_location_types
;
387 elseif ($key === 'url') {
388 $options = $websiteTypes;
390 $sel2[$key] = $options;
394 $js = "<script type='text/javascript'>\n";
395 $formName = 'document.forms.' . $this->_name
;
396 //used to warn for mismatch column count or mismatch mapping
397 CRM_Core_Session
::singleton()->setStatus(NULL);
398 $processor = new CRM_Import_ImportProcessor();
399 $processor->setMappingID($savedMappingID);
400 $processor->setFormName($formName);
401 $processor->setMetadata($this->getContactImportMetadata());
402 $processor->setContactTypeByConstant($this->get('contactType'));
403 $processor->setContactSubType($this->get('contactSubType'));
405 for ($i = 0; $i < $this->_columnCount
; $i++
) {
406 $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
408 if ($this->get('savedMapping')) {
409 list($defaults, $js) = $this->loadSavedMapping($processor, $mappingName, $i, $defaults, $js, $hasColumnNames, $dataPatterns, $columnPatterns);
412 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_0_');\n";
413 if ($hasColumnNames) {
414 // do array search first to see if has mapped key
415 $columnKey = array_search($this->_columnNames
[$i], $this->_mapperFields
);
416 if (isset($this->_fieldUsed
[$columnKey])) {
417 $defaults["mapper[$i]"] = $columnKey;
418 $this->_fieldUsed
[$key] = TRUE;
421 // Infer the default from the column names if we have them
422 $defaults["mapper[$i]"] = [
423 $this->defaultFromColumnName($this->_columnNames
[$i],
431 // Otherwise guess the default from the form of the data
432 $defaults["mapper[$i]"] = [
433 $this->defaultFromData($dataPatterns, $i),
434 // $defaultLocationType->id
439 $sel->setOptions([$sel1, $sel2, $sel3, $sel4]);
442 $js .= "</script>\n";
443 $this->assign('initHideBoxes', $js);
445 //set warning if mismatch in more than
446 if (isset($mappingName) &&
447 ($this->_columnCount
!= count($mappingName))
449 CRM_Core_Session
::singleton()->setStatus(ts('The data columns in this import file appear to be different from the saved mapping. Please verify that you have selected the correct saved mapping before continuing.'));
452 $this->setDefaults($defaults);
457 'name' => ts('Previous'),
461 'name' => ts('Continue'),
462 'spacing' => ' ',
467 'name' => ts('Cancel'),
473 * Global validation rules for the form.
475 * @param array $fields
476 * Posted values of the form.
479 * list of errors to be posted back to the form
481 public static function formRule($fields) {
483 if (!empty($fields['saveMapping'])) {
484 $nameField = CRM_Utils_Array
::value('saveMappingName', $fields);
485 if (empty($nameField)) {
486 $errors['saveMappingName'] = ts('Name is required to save Import Mapping');
489 $mappingTypeId = CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Contact');
490 if (CRM_Core_BAO_Mapping
::checkMapping($nameField, $mappingTypeId)) {
491 $errors['saveMappingName'] = ts('Duplicate Import Mapping Name');
495 $template = CRM_Core_Smarty
::singleton();
496 if (!empty($fields['saveMapping'])) {
497 $template->assign('isCheked', TRUE);
500 if (!empty($errors)) {
502 $assignError = new CRM_Core_Page();
503 $assignError->assign('mappingDetailsError', $_flag);
512 * Process the mapped fields and map it into the uploaded file.
514 public function postProcess() {
515 $params = $this->controller
->exportValues('MapField');
517 //reload the mapfield if load mapping is pressed
518 if (!empty($params['savedMapping'])) {
519 $this->set('savedMapping', $params['savedMapping']);
520 $this->controller
->resetPage($this->_name
);
523 $mapperKeys = $this->controller
->exportValue($this->_name
, 'mapper');
525 $parser = $this->submit($params, $mapperKeys);
527 // add all the necessary variables to the form
532 * Format custom field name.
534 * Combine group and field name to avoid conflict.
536 * @param array $fields
540 public function formatCustomFieldName($fields) {
541 //CRM-2676, replacing the conflict for same custom field name from different custom group.
542 $fieldIds = $formattedFieldNames = [];
543 foreach ($fields as $key => $value) {
544 if ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key)) {
545 $fieldIds[] = $customFieldId;
549 if (!empty($fieldIds) && is_array($fieldIds)) {
550 $groupTitles = CRM_Core_BAO_CustomGroup
::getGroupTitles($fieldIds);
552 if (!empty($groupTitles)) {
553 foreach ($groupTitles as $fId => $values) {
554 $key = "custom_{$fId}";
555 $groupTitle = $values['groupTitle'];
556 $formattedFieldNames[$key] = $fields[$key] . ' :: ' . $groupTitle;
561 return $formattedFieldNames;
565 * Main submit function.
567 * Extracted to add testing & start refactoring.
572 * @return \CRM_Contact_Import_Parser_Contact
573 * @throws \CiviCRM_API3_Exception
575 public function submit($params, $mapperKeys) {
576 $mapper = $mapperKeysMain = $locations = [];
577 $parserParameters = CRM_Contact_Import_Parser_Contact
::getParameterForParser($this->_columnCount
);
579 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
580 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
581 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
582 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
583 $locationTypes['Primary'] = ts('Primary');
585 for ($i = 0; $i < $this->_columnCount
; $i++
) {
587 $fldName = CRM_Utils_Array
::value(0, $mapperKeys[$i]);
588 $selOne = CRM_Utils_Array
::value(1, $mapperKeys[$i]);
589 $selTwo = CRM_Utils_Array
::value(2, $mapperKeys[$i]);
590 $selThree = CRM_Utils_Array
::value(3, $mapperKeys[$i]);
591 $mapper[$i] = $this->_mapperFields
[$mapperKeys[$i][0]];
592 $mapperKeysMain[$i] = $fldName;
594 //need to differentiate non location elements.
595 if ($selOne && (is_numeric($selOne) ||
$selOne === 'Primary')) {
596 if ($fldName === 'url') {
597 $parserParameters['mapperWebsiteType'][$i] = $websiteTypes[$selOne];
600 $locations[$i] = $locationTypes[$selOne];
601 $parserParameters['mapperLocType'][$i] = $selOne;
602 if ($selTwo && is_numeric($selTwo)) {
603 if ($fldName === 'phone') {
604 $parserParameters['mapperPhoneType'][$i] = $phoneTypes[$selTwo];
606 elseif ($fldName === 'im') {
607 $parserParameters['mapperImProvider'][$i] = $imProviders[$selTwo];
613 //relationship contact mapper info.
614 list($id, $first, $second) = CRM_Utils_System
::explode('_', $fldName, 3);
615 if (($first === 'a' && $second === 'b') ||
616 ($first === 'b' && $second === 'a')
618 $parserParameters['mapperRelated'][$i] = $this->_mapperFields
[$fldName];
620 if ($selOne === 'url') {
621 $parserParameters['relatedContactWebsiteType'][$i] = $websiteTypes[$selTwo];
624 $parserParameters['relatedContactLocType'][$i] = CRM_Utils_Array
::value($selTwo, $locationTypes);
626 if ($selOne === 'phone') {
627 $parserParameters['relatedContactPhoneType'][$i] = $phoneTypes[$selThree];
629 elseif ($selOne === 'im') {
630 $parserParameters['relatedContactImProvider'][$i] = $imProviders[$selThree];
635 //get the related contact type.
636 $relationType = new CRM_Contact_DAO_RelationshipType();
637 $relationType->id
= $id;
638 $relationType->find(TRUE);
639 $parserParameters['relatedContactType'][$i] = $relationType->{"contact_type_$second"};
640 $parserParameters['relatedContactDetails'][$i] = $this->_formattedFieldNames
[$parserParameters['relatedContactType'][$i]][$selOne];
645 $this->set('columnNames', $this->_columnNames
);
646 $this->set('websites', $parserParameters['mapperWebsiteType']);
647 $this->set('locations', $locations);
648 $this->set('phones', $parserParameters['mapperPhoneType']);
649 $this->set('ims', $parserParameters['mapperImProvider']);
650 $this->set('related', $parserParameters['mapperRelated']);
651 $this->set('relatedContactType', $parserParameters['relatedContactType']);
652 $this->set('relatedContactDetails', $parserParameters['relatedContactDetails']);
653 $this->set('relatedContactLocType', $parserParameters['relatedContactLocType']);
654 $this->set('relatedContactPhoneType', $parserParameters['relatedContactPhoneType']);
655 $this->set('relatedContactImProvider', $parserParameters['relatedContactImProvider']);
656 $this->set('relatedContactWebsiteType', $parserParameters['relatedContactWebsiteType']);
657 $this->set('mapper', $mapper);
659 // store mapping Id to display it in the preview page
660 $this->set('loadMappingId', CRM_Utils_Array
::value('mappingId', $params));
662 //Updating Mapping Records
663 if (!empty($params['updateMapping'])) {
665 $mappingFields = new CRM_Core_DAO_MappingField();
666 $mappingFields->mapping_id
= $params['mappingId'];
667 $mappingFields->find();
669 $mappingFieldsId = [];
670 while ($mappingFields->fetch()) {
671 if ($mappingFields->id
) {
672 $mappingFieldsId[$mappingFields->column_number
] = $mappingFields->id
;
676 for ($i = 0; $i < $this->_columnCount
; $i++
) {
677 $updateMappingFields = new CRM_Core_DAO_MappingField();
678 $updateMappingFields->id
= CRM_Utils_Array
::value($i, $mappingFieldsId);
679 $updateMappingFields->mapping_id
= $params['mappingId'];
680 $updateMappingFields->column_number
= $i;
682 $mapperKeyParts = explode('_', $mapperKeys[$i][0], 3);
683 $id = isset($mapperKeyParts[0]) ?
$mapperKeyParts[0] : NULL;
684 $first = isset($mapperKeyParts[1]) ?
$mapperKeyParts[1] : NULL;
685 $second = isset($mapperKeyParts[2]) ?
$mapperKeyParts[2] : NULL;
686 if (($first == 'a' && $second == 'b') ||
($first == 'b' && $second == 'a')) {
687 $updateMappingFields->relationship_type_id
= $id;
688 $updateMappingFields->relationship_direction
= "{$first}_{$second}";
689 $updateMappingFields->name
= ucwords(str_replace("_", " ", $mapperKeys[$i][1]));
690 // get phoneType id and provider id separately
691 // before updating mappingFields of phone and IM for related contact, CRM-3140
692 if (CRM_Utils_Array
::value('1', $mapperKeys[$i]) == 'url') {
693 $updateMappingFields->website_type_id
= isset($mapperKeys[$i][2]) ?
$mapperKeys[$i][2] : NULL;
696 if (CRM_Utils_Array
::value('1', $mapperKeys[$i]) == 'phone') {
697 $updateMappingFields->phone_type_id
= isset($mapperKeys[$i][3]) ?
$mapperKeys[$i][3] : NULL;
699 elseif (CRM_Utils_Array
::value('1', $mapperKeys[$i]) == 'im') {
700 $updateMappingFields->im_provider_id
= isset($mapperKeys[$i][3]) ?
$mapperKeys[$i][3] : NULL;
702 $updateMappingFields->location_type_id
= isset($mapperKeys[$i][2]) ?
$mapperKeys[$i][2] : NULL;
706 $updateMappingFields->name
= $mapper[$i];
707 $updateMappingFields->relationship_type_id
= 'NULL';
708 $updateMappingFields->relationship_type_direction
= 'NULL';
709 // to store phoneType id and provider id separately
710 // before updating mappingFields for phone and IM, CRM-3140
711 if (CRM_Utils_Array
::value('0', $mapperKeys[$i]) == 'url') {
712 $updateMappingFields->website_type_id
= isset($mapperKeys[$i][1]) ?
$mapperKeys[$i][1] : NULL;
715 if (CRM_Utils_Array
::value('0', $mapperKeys[$i]) == 'phone') {
716 $updateMappingFields->phone_type_id
= isset($mapperKeys[$i][2]) ?
$mapperKeys[$i][2] : NULL;
718 elseif (CRM_Utils_Array
::value('0', $mapperKeys[$i]) == 'im') {
719 $updateMappingFields->im_provider_id
= isset($mapperKeys[$i][2]) ?
$mapperKeys[$i][2] : NULL;
721 $locationTypeID = $parserParameters['mapperLocType'][$i];
722 // location_type_id is NULL for non-location fields, and for Primary location.
723 $updateMappingFields->location_type_id
= is_numeric($locationTypeID) ?
$locationTypeID : 'null';
726 $updateMappingFields->save();
730 //Saving Mapping Details and Records
731 if (!empty($params['saveMapping'])) {
733 'name' => $params['saveMappingName'],
734 'description' => $params['saveMappingDesc'],
735 'mapping_type_id' => 'Import Contact',
738 $saveMapping = civicrm_api3('Mapping', 'create', $mappingParams);
740 $contactType = $this->get('contactType');
741 switch ($contactType) {
742 case CRM_Import_Parser
::CONTACT_INDIVIDUAL
:
743 $cType = 'Individual';
746 case CRM_Import_Parser
::CONTACT_HOUSEHOLD
:
747 $cType = 'Household';
750 case CRM_Import_Parser
::CONTACT_ORGANIZATION
:
751 $cType = 'Organization';
755 for ($i = 0; $i < $this->_columnCount
; $i++
) {
756 $mappingID = $this->saveMappingField($mapperKeys, $saveMapping, $cType, $i, $mapper, $parserParameters);
758 $this->set('savedMapping', $mappingID);
761 $parser = new CRM_Contact_Import_Parser_Contact($mapperKeysMain, $parserParameters['mapperLocType'], $parserParameters['mapperPhoneType'],
762 $parserParameters['mapperImProvider'], $parserParameters['mapperRelated'], $parserParameters['relatedContactType'],
763 $parserParameters['relatedContactDetails'], $parserParameters['relatedContactLocType'],
764 $parserParameters['relatedContactPhoneType'], $parserParameters['relatedContactImProvider'],
765 $parserParameters['mapperWebsiteType'], $parserParameters['relatedContactWebsiteType']
768 $primaryKeyName = $this->get('primaryKeyName');
769 $statusFieldName = $this->get('statusFieldName');
770 $parser->run($this->_importTableName
,
772 CRM_Import_Parser
::MODE_PREVIEW
,
773 $this->get('contactType'),
778 CRM_Contact_Import_Parser
::DEFAULT_TIMEOUT
,
779 $this->get('contactSubType'),
787 * @param array $saveMapping
788 * @param string $cType
790 * @param array $mapper
791 * @param array $parserParameters
795 protected function saveMappingField($mapperKeys, array $saveMapping, string $cType, int $i, array $mapper, array $parserParameters): int {
796 $saveMappingFields = new CRM_Core_DAO_MappingField();
797 $saveMappingFields->mapping_id
= $saveMapping['id'];
798 $saveMappingFields->contact_type
= $cType;
799 $saveMappingFields->column_number
= $i;
801 $mapperKeyParts = explode('_', $mapperKeys[$i][0], 3);
802 $id = isset($mapperKeyParts[0]) ?
$mapperKeyParts[0] : NULL;
803 $first = isset($mapperKeyParts[1]) ?
$mapperKeyParts[1] : NULL;
804 $second = isset($mapperKeyParts[2]) ?
$mapperKeyParts[2] : NULL;
805 if (($first == 'a' && $second == 'b') ||
($first == 'b' && $second == 'a')) {
806 $saveMappingFields->name
= ucwords(str_replace("_", " ", $mapperKeys[$i][1]));
807 $saveMappingFields->relationship_type_id
= $id;
808 $saveMappingFields->relationship_direction
= "{$first}_{$second}";
809 // to get phoneType id and provider id separately
810 // before saving mappingFields of phone and IM for related contact, CRM-3140
811 if (CRM_Utils_Array
::value('1', $mapperKeys[$i]) == 'url') {
812 $saveMappingFields->website_type_id
= isset($mapperKeys[$i][2]) ?
$mapperKeys[$i][2] : NULL;
815 if (CRM_Utils_Array
::value('1', $mapperKeys[$i]) == 'phone') {
816 $saveMappingFields->phone_type_id
= isset($mapperKeys[$i][3]) ?
$mapperKeys[$i][3] : NULL;
818 elseif (CRM_Utils_Array
::value('1', $mapperKeys[$i]) == 'im') {
819 $saveMappingFields->im_provider_id
= isset($mapperKeys[$i][3]) ?
$mapperKeys[$i][3] : NULL;
821 $saveMappingFields->location_type_id
= (isset($mapperKeys[$i][2]) && $mapperKeys[$i][2] !== 'Primary') ?
$mapperKeys[$i][2] : NULL;
825 $saveMappingFields->name
= $mapper[$i];
826 $locationTypeID = $parserParameters['mapperLocType'][$i];
827 // to get phoneType id and provider id separately
828 // before saving mappingFields of phone and IM, CRM-3140
829 if (CRM_Utils_Array
::value('0', $mapperKeys[$i]) == 'url') {
830 $saveMappingFields->website_type_id
= isset($mapperKeys[$i][1]) ?
$mapperKeys[$i][1] : NULL;
833 if (CRM_Utils_Array
::value('0', $mapperKeys[$i]) == 'phone') {
834 $saveMappingFields->phone_type_id
= isset($mapperKeys[$i][2]) ?
$mapperKeys[$i][2] : NULL;
836 elseif (CRM_Utils_Array
::value('0', $mapperKeys[$i]) == 'im') {
837 $saveMappingFields->im_provider_id
= isset($mapperKeys[$i][2]) ?
$mapperKeys[$i][2] : NULL;
839 $saveMappingFields->location_type_id
= is_numeric($locationTypeID) ?
$locationTypeID : NULL;
841 $saveMappingFields->relationship_type_id
= NULL;
843 $saveMappingFields->save();
844 return $saveMappingFields->mapping_id
;
848 * @param \CRM_Import_ImportProcessor $processor
849 * @param $mappingName
851 * @param array $defaults
853 * @param bool $hasColumnNames
854 * @param array $dataPatterns
855 * @param array $columnPatterns
858 * @throws \CiviCRM_API3_Exception
860 public function loadSavedMapping($processor, $mappingName, $i, $defaults, $js, $hasColumnNames, $dataPatterns, $columnPatterns) {
862 $formName = $processor->getFormName();
863 if (isset($mappingName[$i])) {
864 if ($mappingName[$i] != ts('- do not import -')) {
866 if ($processor->getRelationshipKey($i)) {
867 $defaults["mapper[$i]"] = $processor->getSavedQuickformDefaultsForColumn($i);
868 $js = $processor->getQuickFormJSForField($i);
871 $defaults["mapper[$i]"] = $processor->getSavedQuickformDefaultsForColumn($i);
872 $js .= $processor->getQuickFormJSForField($i);
876 $defaults["mapper[$i]"] = [];
877 for ($k = 1; $k < 4; $k++
) {
878 $js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
883 // this load section to help mapping if we ran out of saved columns when doing Load Mapping
884 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_0_');\n";
886 if ($hasColumnNames) {
887 $defaults["mapper[$i]"] = [$this->defaultFromColumnName($this->_columnNames
[$i], $columnPatterns)];
890 $defaults["mapper[$i]"] = [$this->defaultFromData($dataPatterns, $i)];
893 return [$defaults, $js];