Merge pull request #14868 from civicrm/5.16
[civicrm-core.git] / CRM / Contact / Import / Form / MapField.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33
34 /**
35 * This class gets the name of the file to upload.
36 */
37 class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
38
39
40 /**
41 * An array of all contact fields with
42 * formatted custom field names.
43 *
44 * @var array
45 */
46 protected $_formattedFieldNames;
47
48 /**
49 * On duplicate.
50 *
51 * @var int
52 */
53 public $_onDuplicate;
54
55 protected $_dedupeFields;
56
57 protected static $customFields;
58
59 /**
60 * Attempt to match header labels with our mapper fields.
61 *
62 * FIXME: This is essentially the same function as parent::defaultFromHeader
63 *
64 * @param string $columnName name of column header
65 * @param array $patterns pattern to match for the column
66 *
67 * @return string
68 */
69 public function defaultFromColumnName($columnName, &$patterns) {
70
71 if (!preg_match('/^[a-z0-9 ]$/i', $columnName)) {
72 if ($columnKey = array_search($columnName, $this->_mapperFields)) {
73 $this->_fieldUsed[$columnKey] = TRUE;
74 return $columnKey;
75 }
76 }
77
78 foreach ($patterns as $key => $re) {
79 // Skip empty key/patterns
80 if (!$key || !$re || strlen("$re") < 5) {
81 continue;
82 }
83
84 if (preg_match($re, $columnName)) {
85 $this->_fieldUsed[$key] = TRUE;
86 return $key;
87 }
88 }
89 return '';
90 }
91
92 /**
93 * Set variables up before form is built.
94 */
95 public function preProcess() {
96 $dataSource = $this->get('dataSource');
97 $skipColumnHeader = $this->get('skipColumnHeader');
98 $this->_mapperFields = $this->get('fields');
99 $this->_importTableName = $this->get('importTableName');
100 $this->_onDuplicate = $this->get('onDuplicate');
101 $highlightedFields = array();
102 $highlightedFields[] = 'email';
103 $highlightedFields[] = 'external_identifier';
104 //format custom field names, CRM-2676
105 switch ($this->get('contactType')) {
106 case CRM_Import_Parser::CONTACT_INDIVIDUAL:
107 $contactType = 'Individual';
108 $highlightedFields[] = 'first_name';
109 $highlightedFields[] = 'last_name';
110 break;
111
112 case CRM_Import_Parser::CONTACT_HOUSEHOLD:
113 $contactType = 'Household';
114 $highlightedFields[] = 'household_name';
115 break;
116
117 case CRM_Import_Parser::CONTACT_ORGANIZATION:
118 $contactType = 'Organization';
119 $highlightedFields[] = 'organization_name';
120 break;
121 }
122 $this->_contactType = $contactType;
123 if ($this->_onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
124 unset($this->_mapperFields['id']);
125 }
126 else {
127 $highlightedFields[] = 'id';
128 }
129
130 if ($this->_onDuplicate != CRM_Import_Parser::DUPLICATE_NOCHECK) {
131 //Mark Dedupe Rule Fields as required, since it's used in matching contact
132 foreach (array(
133 'Individual',
134 'Household',
135 'Organization',
136 ) as $cType) {
137 $ruleParams = array(
138 'contact_type' => $cType,
139 'used' => 'Unsupervised',
140 );
141 $this->_dedupeFields[$cType] = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
142 }
143
144 //Modify mapper fields title if fields are present in dedupe rule
145 if (is_array($this->_dedupeFields[$contactType])) {
146 foreach ($this->_dedupeFields[$contactType] as $val) {
147 if ($valTitle = CRM_Utils_Array::value($val, $this->_mapperFields)) {
148 $this->_mapperFields[$val] = $valTitle . ' (match to contact)';
149 }
150 }
151 }
152 }
153 // retrieve and highlight required custom fields
154 $formattedFieldNames = $this->formatCustomFieldName($this->_mapperFields);
155 self::$customFields = CRM_Core_BAO_CustomField::getFields($this->_contactType);
156 foreach (self::$customFields as $key => $attr) {
157 if (!empty($attr['is_required'])) {
158 $highlightedFields[] = "custom_$key";
159 }
160 }
161 $this->assign('highlightedFields', $highlightedFields);
162 $this->_formattedFieldNames[$contactType] = $this->_mapperFields = array_merge($this->_mapperFields, $formattedFieldNames);
163
164 $columnNames = array();
165 //get original col headers from csv if present.
166 if ($dataSource == 'CRM_Import_DataSource_CSV' && $skipColumnHeader) {
167 $columnNames = $this->get('originalColHeader');
168 }
169 else {
170 // get the field names from the temp. DB table
171 $dao = new CRM_Core_DAO();
172 $db = $dao->getDatabaseConnection();
173
174 $columnsQuery = "SHOW FIELDS FROM $this->_importTableName
175 WHERE Field NOT LIKE '\_%'";
176 $columnsResult = $db->query($columnsQuery);
177 while ($row = $columnsResult->fetchRow(DB_FETCHMODE_ASSOC)) {
178 $columnNames[] = $row['Field'];
179 }
180 }
181
182 $showColNames = TRUE;
183 if ($dataSource == 'CRM_Import_DataSource_CSV' && !$skipColumnHeader) {
184 $showColNames = FALSE;
185 }
186 $this->assign('showColNames', $showColNames);
187
188 $this->_columnCount = count($columnNames);
189 $this->_columnNames = $columnNames;
190 $this->assign('columnNames', $columnNames);
191 //$this->_columnCount = $this->get( 'columnCount' );
192 $this->assign('columnCount', $this->_columnCount);
193 $this->_dataValues = $this->get('dataValues');
194 $this->assign('dataValues', $this->_dataValues);
195 $this->assign('rowDisplayCount', 2);
196 }
197
198 /**
199 * Build the form object.
200 */
201 public function buildQuickForm() {
202 //to save the current mappings
203 if (!$this->get('savedMapping')) {
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'));
208 }
209 else {
210 $savedMapping = $this->get('savedMapping');
211
212 list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider, $mappingRelation, $mappingOperator, $mappingValue, $mappingWebsiteType) = CRM_Core_BAO_Mapping::getMappingFields($savedMapping, TRUE);
213
214 //get loaded Mapping Fields
215 $mappingName = CRM_Utils_Array::value(1, $mappingName);
216 $mappingLocation = CRM_Utils_Array::value(1, $mappingLocation);
217 $mappingPhoneType = CRM_Utils_Array::value(1, $mappingPhoneType);
218 $mappingImProvider = CRM_Utils_Array::value(1, $mappingImProvider);
219 $mappingRelation = CRM_Utils_Array::value(1, $mappingRelation);
220 $mappingWebsiteType = CRM_Utils_Array::value(1, $mappingWebsiteType);
221
222 $this->assign('loadedMapping', $savedMapping);
223 $this->set('loadedMapping', $savedMapping);
224
225 $params = array('id' => $savedMapping);
226 $temp = array();
227 $mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp);
228
229 $this->assign('savedName', $mappingDetails->name);
230
231 $this->add('hidden', 'mappingId', $savedMapping);
232
233 $this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
234 $saveDetailsName = ts('Save as a new field mapping');
235 $this->add('text', 'saveMappingName', ts('Name'));
236 $this->add('text', 'saveMappingDesc', ts('Description'));
237 }
238
239 $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)"));
240
241 $this->addFormRule(array('CRM_Contact_Import_Form_MapField', 'formRule'));
242
243 //-------- end of saved mapping stuff ---------
244
245 $defaults = array();
246 $mapperKeys = array_keys($this->_mapperFields);
247 $hasColumnNames = !empty($this->_columnNames);
248 $columnPatterns = $this->get('columnPatterns');
249 $dataPatterns = $this->get('dataPatterns');
250 $hasLocationTypes = $this->get('fieldTypes');
251
252 $this->_location_types = array('Primary' => ts('Primary')) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
253 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
254
255 // Pass default location to js
256 if ($defaultLocationType) {
257 $this->assign('defaultLocationType', $defaultLocationType->id);
258 $this->assign('defaultLocationTypeLabel', $this->_location_types[$defaultLocationType->id]);
259 }
260
261 /* Initialize all field usages to false */
262 foreach ($mapperKeys as $key) {
263 $this->_fieldUsed[$key] = FALSE;
264 }
265
266 $sel1 = $this->_mapperFields;
267 $sel2[''] = NULL;
268
269 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
270 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
271 $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
272
273 foreach ($this->_location_types as $key => $value) {
274 $sel3['phone'][$key] = &$phoneTypes;
275 //build array for IM service provider type for contact
276 $sel3['im'][$key] = &$imProviders;
277 }
278
279 $sel4 = NULL;
280
281 // store and cache all relationship types
282 $contactRelation = new CRM_Contact_DAO_RelationshipType();
283 $contactRelation->find();
284 while ($contactRelation->fetch()) {
285 $contactRelationCache[$contactRelation->id] = array();
286 $contactRelationCache[$contactRelation->id]['contact_type_a'] = $contactRelation->contact_type_a;
287 $contactRelationCache[$contactRelation->id]['contact_sub_type_a'] = $contactRelation->contact_sub_type_a;
288 $contactRelationCache[$contactRelation->id]['contact_type_b'] = $contactRelation->contact_type_b;
289 $contactRelationCache[$contactRelation->id]['contact_sub_type_b'] = $contactRelation->contact_sub_type_b;
290 }
291 $highlightedFields = $highlightedRelFields = array();
292
293 $highlightedFields['email'] = 'All';
294 $highlightedFields['external_identifier'] = 'All';
295 $highlightedFields['first_name'] = 'Individual';
296 $highlightedFields['last_name'] = 'Individual';
297 $highlightedFields['household_name'] = 'Household';
298 $highlightedFields['organization_name'] = 'Organization';
299
300 foreach ($mapperKeys as $key) {
301 // check if there is a _a_b or _b_a in the key
302 if (strpos($key, '_a_b') || strpos($key, '_b_a')) {
303 list($id, $first, $second) = explode('_', $key);
304 }
305 else {
306 $id = $first = $second = NULL;
307 }
308 if (($first == 'a' && $second == 'b') || ($first == 'b' && $second == 'a')) {
309 $cType = $contactRelationCache[$id]["contact_type_{$second}"];
310
311 //CRM-5125 for contact subtype specific relationshiptypes
312 $cSubType = NULL;
313 if (!empty($contactRelationCache[$id]["contact_sub_type_{$second}"])) {
314 $cSubType = $contactRelationCache[$id]["contact_sub_type_{$second}"];
315 }
316
317 if (!$cType) {
318 $cType = 'All';
319 }
320
321 $relatedFields = CRM_Contact_BAO_Contact::importableFields($cType);
322 unset($relatedFields['']);
323 $values = array();
324 foreach ($relatedFields as $name => $field) {
325 $values[$name] = $field['title'];
326 if (isset($hasLocationTypes[$name])) {
327 $sel3[$key][$name] = $this->_location_types;
328 }
329 elseif ($name == 'url') {
330 $sel3[$key][$name] = $websiteTypes;
331 }
332 else {
333 $sel3[$name] = NULL;
334 }
335 }
336
337 //fix to append custom group name to field name, CRM-2676
338 if (empty($this->_formattedFieldNames[$cType]) || $cType == $this->_contactType) {
339 $this->_formattedFieldNames[$cType] = $this->formatCustomFieldName($values);
340 }
341
342 $this->_formattedFieldNames[$cType] = array_merge($values, $this->_formattedFieldNames[$cType]);
343
344 //Modified the Relationship fields if the fields are
345 //present in dedupe rule
346 if ($this->_onDuplicate != CRM_Import_Parser::DUPLICATE_NOCHECK && !empty($this->_dedupeFields[$cType]) &&
347 is_array($this->_dedupeFields[$cType])
348 ) {
349 static $cTypeArray = array();
350 if ($cType != $this->_contactType && !in_array($cType, $cTypeArray)) {
351 foreach ($this->_dedupeFields[$cType] as $val) {
352 if ($valTitle = CRM_Utils_Array::value($val, $this->_formattedFieldNames[$cType])) {
353 $this->_formattedFieldNames[$cType][$val] = $valTitle . ' (match to contact)';
354 }
355 }
356 $cTypeArray[] = $cType;
357 }
358 }
359
360 foreach ($highlightedFields as $k => $v) {
361 if ($v == $cType || $v == 'All') {
362 $highlightedRelFields[$key][] = $k;
363 }
364 }
365 $this->assign('highlightedRelFields', $highlightedRelFields);
366 $sel2[$key] = $this->_formattedFieldNames[$cType];
367
368 if (!empty($cSubType)) {
369 //custom fields for sub type
370 $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($cSubType);
371
372 if (!empty($subTypeFields)) {
373 $subType = NULL;
374 foreach ($subTypeFields as $customSubTypeField => $details) {
375 $subType[$customSubTypeField] = $details['title'];
376 $sel2[$key] = array_merge($sel2[$key], $this->formatCustomFieldName($subType));
377 }
378 }
379 }
380
381 foreach ($this->_location_types as $k => $value) {
382 $sel4[$key]['phone'][$k] = &$phoneTypes;
383 //build array of IM service provider for related contact
384 $sel4[$key]['im'][$k] = &$imProviders;
385 }
386 }
387 else {
388 $options = NULL;
389 if (!empty($hasLocationTypes[$key])) {
390 $options = $this->_location_types;
391 }
392 elseif ($key == 'url') {
393 $options = $websiteTypes;
394 }
395 $sel2[$key] = $options;
396 }
397 }
398
399 $js = "<script type='text/javascript'>\n";
400 $formName = 'document.forms.' . $this->_name;
401 //used to warn for mismatch column count or mismatch mapping
402 $warning = 0;
403 for ($i = 0; $i < $this->_columnCount; $i++) {
404 $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', array(1 => $i)), NULL);
405 $jsSet = FALSE;
406 if ($this->get('savedMapping')) {
407 if (isset($mappingName[$i])) {
408 if ($mappingName[$i] != ts('- do not import -')) {
409
410 if (isset($mappingRelation[$i])) {
411 // relationship mapping
412 switch ($this->get('contactType')) {
413 case CRM_Import_Parser::CONTACT_INDIVIDUAL:
414 $contactType = 'Individual';
415 break;
416
417 case CRM_Import_Parser::CONTACT_HOUSEHOLD:
418 $contactType = 'Household';
419 break;
420
421 case CRM_Import_Parser::CONTACT_ORGANIZATION:
422 $contactType = 'Organization';
423 }
424 //CRM-5125
425 $contactSubType = NULL;
426 if ($this->get('contactSubType')) {
427 $contactSubType = $this->get('contactSubType');
428 }
429
430 $relations = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $contactType,
431 FALSE, 'label', TRUE, $contactSubType
432 );
433
434 foreach ($relations as $key => $var) {
435 if ($key == $mappingRelation[$i]) {
436 $relation = $key;
437 break;
438 }
439 }
440
441 $contactDetails = strtolower(str_replace(" ", "_", $mappingName[$i]));
442 $websiteTypeId = isset($mappingWebsiteType[$i]) ? $mappingWebsiteType[$i] : NULL;
443 $locationId = isset($mappingLocation[$i]) ? $mappingLocation[$i] : 0;
444 $phoneType = isset($mappingPhoneType[$i]) ? $mappingPhoneType[$i] : NULL;
445 //get provider id from saved mappings
446 $imProvider = isset($mappingImProvider[$i]) ? $mappingImProvider[$i] : NULL;
447
448 if ($websiteTypeId) {
449 $defaults["mapper[$i]"] = array($relation, $contactDetails, $websiteTypeId);
450 if (!$websiteTypeId) {
451 $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
452 }
453 }
454 else {
455 // default for IM/phone when mapping with relation is true
456 $typeId = NULL;
457 if (isset($phoneType)) {
458 $typeId = $phoneType;
459 }
460 elseif (isset($imProvider)) {
461 $typeId = $imProvider;
462 }
463 $defaults["mapper[$i]"] = array($relation, $contactDetails, $locationId, $typeId);
464 if (!$locationId) {
465 $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
466 }
467 }
468 // fix for edge cases, CRM-4954
469 if ($contactDetails == 'image_url') {
470 $contactDetails = str_replace('url', 'URL', $contactDetails);
471 }
472
473 if (!$contactDetails) {
474 $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
475 }
476
477 if ((!$phoneType) && (!$imProvider)) {
478 $js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
479 }
480 //$js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
481 $jsSet = TRUE;
482 }
483 else {
484 $mappingHeader = array_keys($this->_mapperFields, $mappingName[$i]);
485 $websiteTypeId = isset($mappingWebsiteType[$i]) ? $mappingWebsiteType[$i] : NULL;
486 $locationId = isset($mappingLocation[$i]) ? $mappingLocation[$i] : 0;
487 $phoneType = isset($mappingPhoneType[$i]) ? $mappingPhoneType[$i] : NULL;
488 // get IM service provider id
489 $imProvider = isset($mappingImProvider[$i]) ? $mappingImProvider[$i] : NULL;
490
491 if ($websiteTypeId) {
492 if (!$websiteTypeId) {
493 $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
494 }
495 $defaults["mapper[$i]"] = array($mappingHeader[0], $websiteTypeId);
496 }
497 else {
498 if (!$locationId) {
499 $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
500 }
501 //default for IM/phone without related contact
502 $typeId = NULL;
503 if (isset($phoneType)) {
504 $typeId = $phoneType;
505 }
506 elseif (isset($imProvider)) {
507 $typeId = $imProvider;
508 }
509 $defaults["mapper[$i]"] = array($mappingHeader[0], $locationId, $typeId);
510 }
511
512 if ((!$phoneType) && (!$imProvider)) {
513 $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
514 }
515
516 $js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
517
518 $jsSet = TRUE;
519 }
520 }
521 else {
522 $defaults["mapper[$i]"] = array();
523 }
524 if (!$jsSet) {
525 for ($k = 1; $k < 4; $k++) {
526 $js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
527 }
528 }
529 }
530 else {
531 // this load section to help mapping if we ran out of saved columns when doing Load Mapping
532 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_0_');\n";
533
534 if ($hasColumnNames) {
535 $defaults["mapper[$i]"] = array($this->defaultFromColumnName($this->_columnNames[$i], $columnPatterns));
536 }
537 else {
538 $defaults["mapper[$i]"] = array($this->defaultFromData($dataPatterns, $i));
539 }
540 }
541 //end of load mapping
542 }
543 else {
544 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_0_');\n";
545 if ($hasColumnNames) {
546 // do array search first to see if has mapped key
547 $columnKey = '';
548 $columnKey = array_search($this->_columnNames[$i], $this->_mapperFields);
549 if (isset($this->_fieldUsed[$columnKey])) {
550 $defaults["mapper[$i]"] = $columnKey;
551 $this->_fieldUsed[$key] = TRUE;
552 }
553 else {
554 // Infer the default from the column names if we have them
555 $defaults["mapper[$i]"] = array(
556 $this->defaultFromColumnName($this->_columnNames[$i],
557 $columnPatterns
558 ),
559 0,
560 );
561 }
562 }
563 else {
564 // Otherwise guess the default from the form of the data
565 $defaults["mapper[$i]"] = array(
566 $this->defaultFromData($dataPatterns, $i),
567 // $defaultLocationType->id
568 0,
569 );
570 }
571 }
572 $sel->setOptions(array($sel1, $sel2, $sel3, $sel4));
573 }
574
575 $js .= "</script>\n";
576 $this->assign('initHideBoxes', $js);
577
578 //set warning if mismatch in more than
579 if (isset($mappingName) &&
580 ($this->_columnCount != count($mappingName))
581 ) {
582 $warning++;
583 }
584
585 if ($warning != 0 && $this->get('savedMapping')) {
586 $session = CRM_Core_Session::singleton();
587 $session->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.'));
588 }
589 else {
590 $session = CRM_Core_Session::singleton();
591 $session->setStatus(NULL);
592 }
593
594 $this->setDefaults($defaults);
595
596 $this->addButtons(array(
597 array(
598 'type' => 'back',
599 'name' => ts('Previous'),
600 ),
601 array(
602 'type' => 'next',
603 'name' => ts('Continue'),
604 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
605 'isDefault' => TRUE,
606 ),
607 array(
608 'type' => 'cancel',
609 'name' => ts('Cancel'),
610 ),
611 )
612 );
613 }
614
615 /**
616 * Global validation rules for the form.
617 *
618 * @param array $fields
619 * Posted values of the form.
620 *
621 * @return array
622 * list of errors to be posted back to the form
623 */
624 public static function formRule($fields) {
625 $errors = array();
626 if (!empty($fields['saveMapping'])) {
627 $nameField = CRM_Utils_Array::value('saveMappingName', $fields);
628 if (empty($nameField)) {
629 $errors['saveMappingName'] = ts('Name is required to save Import Mapping');
630 }
631 else {
632 $mappingTypeId = CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Contact');
633 if (CRM_Core_BAO_Mapping::checkMapping($nameField, $mappingTypeId)) {
634 $errors['saveMappingName'] = ts('Duplicate Import Mapping Name');
635 }
636 }
637 }
638 $template = CRM_Core_Smarty::singleton();
639 if (!empty($fields['saveMapping'])) {
640 $template->assign('isCheked', TRUE);
641 }
642
643 if (!empty($errors)) {
644 $_flag = 1;
645 $assignError = new CRM_Core_Page();
646 $assignError->assign('mappingDetailsError', $_flag);
647 return $errors;
648 }
649 else {
650 return TRUE;
651 }
652 }
653
654 /**
655 * Process the mapped fields and map it into the uploaded file.
656 */
657 public function postProcess() {
658 $params = $this->controller->exportValues('MapField');
659
660 //reload the mapfield if load mapping is pressed
661 if (!empty($params['savedMapping'])) {
662 $this->set('savedMapping', $params['savedMapping']);
663 $this->controller->resetPage($this->_name);
664 return;
665 }
666 $mapperKeys = $this->controller->exportValue($this->_name, 'mapper');
667
668 $parser = $this->submit($params, $mapperKeys);
669
670 // add all the necessary variables to the form
671 $parser->set($this);
672 }
673
674 /**
675 * Format custom field name.
676 *
677 * Combine group and field name to avoid conflict.
678 *
679 * @param array $fields
680 *
681 * @return array
682 */
683 public function formatCustomFieldName(&$fields) {
684 //CRM-2676, replacing the conflict for same custom field name from different custom group.
685 $fieldIds = $formattedFieldNames = array();
686 foreach ($fields as $key => $value) {
687 if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key)) {
688 $fieldIds[] = $customFieldId;
689 }
690 }
691
692 if (!empty($fieldIds) && is_array($fieldIds)) {
693 $groupTitles = CRM_Core_BAO_CustomGroup::getGroupTitles($fieldIds);
694
695 if (!empty($groupTitles)) {
696 foreach ($groupTitles as $fId => $values) {
697 $key = "custom_{$fId}";
698 $groupTitle = $values['groupTitle'];
699 $formattedFieldNames[$key] = $fields[$key] . ' :: ' . $groupTitle;
700 }
701 }
702 }
703
704 return $formattedFieldNames;
705 }
706
707 /**
708 * Main submit function.
709 *
710 * Extracted to add testing & start refactoring.
711 *
712 * @param $params
713 * @param $mapperKeys
714 *
715 * @return \CRM_Contact_Import_Parser_Contact
716 * @throws \CiviCRM_API3_Exception
717 */
718 public function submit($params, $mapperKeys) {
719 $mapper = $mapperKeysMain = $locations = array();
720 $parserParameters = CRM_Contact_Import_Parser_Contact::getParameterForParser($this->_columnCount);
721
722 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
723 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
724 $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
725 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
726 $locationTypes['Primary'] = ts('Primary');
727
728 for ($i = 0; $i < $this->_columnCount; $i++) {
729
730 $fldName = CRM_Utils_Array::value(0, $mapperKeys[$i]);
731 $selOne = CRM_Utils_Array::value(1, $mapperKeys[$i]);
732 $selTwo = CRM_Utils_Array::value(2, $mapperKeys[$i]);
733 $selThree = CRM_Utils_Array::value(3, $mapperKeys[$i]);
734 $mapper[$i] = $this->_mapperFields[$mapperKeys[$i][0]];
735 $mapperKeysMain[$i] = $fldName;
736
737 //need to differentiate non location elements.
738 if ($selOne && (is_numeric($selOne) || $selOne === 'Primary')) {
739 if ($fldName == 'url') {
740 $parserParameters['mapperWebsiteType'][$i] = $websiteTypes[$selOne];
741 }
742 else {
743 $locations[$i] = $locationTypes[$selOne];
744 $parserParameters['mapperLocType'][$i] = $selOne;
745 if ($selTwo && is_numeric($selTwo)) {
746 if ($fldName == 'phone') {
747 $parserParameters['mapperPhoneType'][$i] = $phoneTypes[$selTwo];
748 }
749 elseif ($fldName == 'im') {
750 $parserParameters['mapperImProvider'][$i] = $imProviders[$selTwo];
751 }
752 }
753 }
754 }
755
756 //relationship contact mapper info.
757 list($id, $first, $second) = CRM_Utils_System::explode('_', $fldName, 3);
758 if (($first == 'a' && $second == 'b') ||
759 ($first == 'b' && $second == 'a')
760 ) {
761 $parserParameters['mapperRelated'][$i] = $this->_mapperFields[$fldName];
762 if ($selOne) {
763 if ($selOne == 'url') {
764 $parserParameters['relatedContactWebsiteType'][$i] = $websiteTypes[$selTwo];
765 }
766 else {
767 $parserParameters['relatedContactLocType'][$i] = CRM_Utils_Array::value($selTwo, $locationTypes);
768 if ($selThree) {
769 if ($selOne == 'phone') {
770 $parserParameters['relatedContactPhoneType'][$i] = $phoneTypes[$selThree];
771 }
772 elseif ($selOne == 'im') {
773 $parserParameters['relatedContactImProvider'][$i] = $imProviders[$selThree];
774 }
775 }
776 }
777
778 //get the related contact type.
779 $relationType = new CRM_Contact_DAO_RelationshipType();
780 $relationType->id = $id;
781 $relationType->find(TRUE);
782 $parserParameters['relatedContactType'][$i] = $relationType->{"contact_type_$second"};
783 $parserParameters['relatedContactDetails'][$i] = $this->_formattedFieldNames[$parserParameters['relatedContactType'][$i]][$selOne];
784 }
785 }
786 }
787
788 $this->set('columnNames', $this->_columnNames);
789 $this->set('websites', $parserParameters['mapperWebsiteType']);
790 $this->set('locations', $locations);
791 $this->set('phones', $parserParameters['mapperPhoneType']);
792 $this->set('ims', $parserParameters['mapperImProvider']);
793 $this->set('related', $parserParameters['mapperRelated']);
794 $this->set('relatedContactType', $parserParameters['relatedContactType']);
795 $this->set('relatedContactDetails', $parserParameters['relatedContactDetails']);
796 $this->set('relatedContactLocType', $parserParameters['relatedContactLocType']);
797 $this->set('relatedContactPhoneType', $parserParameters['relatedContactPhoneType']);
798 $this->set('relatedContactImProvider', $parserParameters['relatedContactImProvider']);
799 $this->set('relatedContactWebsiteType', $parserParameters['relatedContactWebsiteType']);
800 $this->set('mapper', $mapper);
801
802 // store mapping Id to display it in the preview page
803 $this->set('loadMappingId', CRM_Utils_Array::value('mappingId', $params));
804
805 //Updating Mapping Records
806 if (!empty($params['updateMapping'])) {
807
808 $mappingFields = new CRM_Core_DAO_MappingField();
809 $mappingFields->mapping_id = $params['mappingId'];
810 $mappingFields->find();
811
812 $mappingFieldsId = array();
813 while ($mappingFields->fetch()) {
814 if ($mappingFields->id) {
815 $mappingFieldsId[$mappingFields->column_number] = $mappingFields->id;
816 }
817 }
818
819 for ($i = 0; $i < $this->_columnCount; $i++) {
820 $updateMappingFields = new CRM_Core_DAO_MappingField();
821 $updateMappingFields->id = CRM_Utils_Array::value($i, $mappingFieldsId);
822 $updateMappingFields->mapping_id = $params['mappingId'];
823 $updateMappingFields->column_number = $i;
824
825 $mapperKeyParts = explode('_', $mapperKeys[$i][0], 3);
826 $id = isset($mapperKeyParts[0]) ? $mapperKeyParts[0] : NULL;
827 $first = isset($mapperKeyParts[1]) ? $mapperKeyParts[1] : NULL;
828 $second = isset($mapperKeyParts[2]) ? $mapperKeyParts[2] : NULL;
829 if (($first == 'a' && $second == 'b') || ($first == 'b' && $second == 'a')) {
830 $updateMappingFields->relationship_type_id = $id;
831 $updateMappingFields->relationship_direction = "{$first}_{$second}";
832 $updateMappingFields->name = ucwords(str_replace("_", " ", $mapperKeys[$i][1]));
833 // get phoneType id and provider id separately
834 // before updating mappingFields of phone and IM for related contact, CRM-3140
835 if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'url') {
836 $updateMappingFields->website_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL;
837 }
838 else {
839 if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'phone') {
840 $updateMappingFields->phone_type_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : NULL;
841 }
842 elseif (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'im') {
843 $updateMappingFields->im_provider_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : NULL;
844 }
845 $updateMappingFields->location_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL;
846 }
847 }
848 else {
849 $updateMappingFields->name = $mapper[$i];
850 $updateMappingFields->relationship_type_id = 'NULL';
851 $updateMappingFields->relationship_type_direction = 'NULL';
852 // to store phoneType id and provider id separately
853 // before updating mappingFields for phone and IM, CRM-3140
854 if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'url') {
855 $updateMappingFields->website_type_id = isset($mapperKeys[$i][1]) ? $mapperKeys[$i][1] : NULL;
856 }
857 else {
858 if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'phone') {
859 $updateMappingFields->phone_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL;
860 }
861 elseif (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'im') {
862 $updateMappingFields->im_provider_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL;
863 }
864 $locationTypeID = $parserParameters['mapperLocType'][$i];
865 // location_type_id is NULL for non-location fields, and for Primary location.
866 $updateMappingFields->location_type_id = is_numeric($locationTypeID) ? $locationTypeID : 'null';
867 }
868 }
869 $updateMappingFields->save();
870 }
871 }
872
873 //Saving Mapping Details and Records
874 if (!empty($params['saveMapping'])) {
875 $mappingParams = array(
876 'name' => $params['saveMappingName'],
877 'description' => $params['saveMappingDesc'],
878 'mapping_type_id' => 'Import Contact',
879 );
880
881 $saveMapping = civicrm_api3('Mapping', 'create', $mappingParams);
882
883 $contactType = $this->get('contactType');
884 switch ($contactType) {
885 case CRM_Import_Parser::CONTACT_INDIVIDUAL:
886 $cType = 'Individual';
887 break;
888
889 case CRM_Import_Parser::CONTACT_HOUSEHOLD:
890 $cType = 'Household';
891 break;
892
893 case CRM_Import_Parser::CONTACT_ORGANIZATION:
894 $cType = 'Organization';
895 }
896
897 $mappingID = NULL;
898 for ($i = 0; $i < $this->_columnCount; $i++) {
899 $mappingID = $this->saveMappingField($mapperKeys, $saveMapping, $cType, $i, $mapper, $parserParameters);
900 }
901 $this->set('savedMapping', $mappingID);
902 }
903
904 $parser = new CRM_Contact_Import_Parser_Contact($mapperKeysMain, $parserParameters['mapperLocType'], $parserParameters['mapperPhoneType'],
905 $parserParameters['mapperImProvider'], $parserParameters['mapperRelated'], $parserParameters['relatedContactType'],
906 $parserParameters['relatedContactDetails'], $parserParameters['relatedContactLocType'],
907 $parserParameters['relatedContactPhoneType'], $parserParameters['relatedContactImProvider'],
908 $parserParameters['mapperWebsiteType'], $parserParameters['relatedContactWebsiteType']
909 );
910
911 $primaryKeyName = $this->get('primaryKeyName');
912 $statusFieldName = $this->get('statusFieldName');
913 $parser->run($this->_importTableName,
914 $mapper,
915 CRM_Import_Parser::MODE_PREVIEW,
916 $this->get('contactType'),
917 $primaryKeyName,
918 $statusFieldName,
919 $this->_onDuplicate,
920 NULL, NULL, FALSE,
921 CRM_Contact_Import_Parser::DEFAULT_TIMEOUT,
922 $this->get('contactSubType'),
923 $this->get('dedupe')
924 );
925 return $parser;
926 }
927
928 /**
929 * @param $mapperKeys
930 * @param array $saveMapping
931 * @param string $cType
932 * @param int $i
933 * @param array $mapper
934 * @param array $parserParameters
935 *
936 * @return int
937 */
938 protected function saveMappingField($mapperKeys, array $saveMapping, string $cType, int $i, array $mapper, array $parserParameters): int {
939 $saveMappingFields = new CRM_Core_DAO_MappingField();
940 $saveMappingFields->mapping_id = $saveMapping['id'];
941 $saveMappingFields->contact_type = $cType;
942 $saveMappingFields->column_number = $i;
943
944 $mapperKeyParts = explode('_', $mapperKeys[$i][0], 3);
945 $id = isset($mapperKeyParts[0]) ? $mapperKeyParts[0] : NULL;
946 $first = isset($mapperKeyParts[1]) ? $mapperKeyParts[1] : NULL;
947 $second = isset($mapperKeyParts[2]) ? $mapperKeyParts[2] : NULL;
948 if (($first == 'a' && $second == 'b') || ($first == 'b' && $second == 'a')) {
949 $saveMappingFields->name = ucwords(str_replace("_", " ", $mapperKeys[$i][1]));
950 $saveMappingFields->relationship_type_id = $id;
951 $saveMappingFields->relationship_direction = "{$first}_{$second}";
952 // to get phoneType id and provider id separately
953 // before saving mappingFields of phone and IM for related contact, CRM-3140
954 if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'url') {
955 $saveMappingFields->website_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL;
956 }
957 else {
958 if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'phone') {
959 $saveMappingFields->phone_type_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : NULL;
960 }
961 elseif (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'im') {
962 $saveMappingFields->im_provider_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : NULL;
963 }
964 $saveMappingFields->location_type_id = (isset($mapperKeys[$i][2]) && $mapperKeys[$i][2] !== 'Primary') ? $mapperKeys[$i][2] : NULL;
965 }
966 }
967 else {
968 $saveMappingFields->name = $mapper[$i];
969 $locationTypeID = $parserParameters['mapperLocType'][$i];
970 // to get phoneType id and provider id separately
971 // before saving mappingFields of phone and IM, CRM-3140
972 if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'url') {
973 $saveMappingFields->website_type_id = isset($mapperKeys[$i][1]) ? $mapperKeys[$i][1] : NULL;
974 }
975 else {
976 if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'phone') {
977 $saveMappingFields->phone_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL;
978 }
979 elseif (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'im') {
980 $saveMappingFields->im_provider_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL;
981 }
982 $saveMappingFields->location_type_id = is_numeric($locationTypeID) ? $locationTypeID : NULL;
983 }
984 $saveMappingFields->relationship_type_id = NULL;
985 }
986 $saveMappingFields->save();
987 return $saveMappingFields->mapping_id;
988 }
989
990 }