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