Remove jsSet & just construct the if better.
[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 use CRM_Contact_Import_MetadataTrait;
40
41 /**
42 * An array of all contact fields with
43 * formatted custom field names.
44 *
45 * @var array
46 */
47 protected $_formattedFieldNames;
48
49 /**
50 * On duplicate.
51 *
52 * @var int
53 */
54 public $_onDuplicate;
55
56 protected $_dedupeFields;
57
58 protected static $customFields;
59
60 /**
61 * Attempt to match header labels with our mapper fields.
62 *
63 * FIXME: This is essentially the same function as parent::defaultFromHeader
64 *
65 * @param string $columnName name of column header
66 * @param array $patterns pattern to match for the column
67 *
68 * @return string
69 */
70 public function defaultFromColumnName($columnName, $patterns) {
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
93 /**
94 * Set variables up before form is built.
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');
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';
111 break;
112
113 case CRM_Import_Parser::CONTACT_HOUSEHOLD:
114 $contactType = 'Household';
115 $highlightedFields[] = 'household_name';
116 break;
117
118 case CRM_Import_Parser::CONTACT_ORGANIZATION:
119 $contactType = 'Organization';
120 $highlightedFields[] = 'organization_name';
121 break;
122 }
123 $this->_contactType = $contactType;
124 if ($this->_onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
125 unset($this->_mapperFields['id']);
126 }
127 else {
128 $highlightedFields[] = 'id';
129 }
130
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) {
134 $ruleParams = [
135 'contact_type' => $cType,
136 'used' => 'Unsupervised',
137 ];
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 }
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";
156 }
157 }
158 $this->assign('highlightedFields', $highlightedFields);
159 $this->_formattedFieldNames[$contactType] = $this->_mapperFields = array_merge($this->_mapperFields, $formattedFieldNames);
160
161 $columnNames = [];
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;
180 if ($dataSource === 'CRM_Import_DataSource_CSV' && !$skipColumnHeader) {
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 /**
196 * Build the form object.
197 *
198 * @throws \CiviCRM_API3_Exception
199 */
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'));
208 }
209 else {
210 $savedMapping = $this->get('savedMapping');
211
212 list($mappingName) = CRM_Core_BAO_Mapping::getMappingFields($savedMapping, TRUE);
213
214 //get loaded Mapping Fields
215 $mappingName = CRM_Utils_Array::value(1, $mappingName);
216
217 $this->assign('loadedMapping', $savedMapping);
218 $this->set('loadedMapping', $savedMapping);
219
220 $params = ['id' => $savedMapping];
221 $temp = [];
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
234 $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, ['onclick' => "showSaveDetails(this)"]);
235
236 $this->addFormRule(['CRM_Contact_Import_Form_MapField', 'formRule']);
237
238 //-------- end of saved mapping stuff ---------
239
240 $defaults = [];
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');
246
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();
249
250 // Pass default location to js
251 if ($defaultLocationType) {
252 $this->assign('defaultLocationType', $defaultLocationType->id);
253 $this->assign('defaultLocationTypeLabel', $this->_location_types[$defaultLocationType->id]);
254 }
255
256 /* Initialize all field usages to false */
257 foreach ($mapperKeys as $key) {
258 $this->_fieldUsed[$key] = FALSE;
259 }
260
261 $sel1 = $this->_mapperFields;
262 $sel2[''] = NULL;
263
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');
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()) {
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;
285 }
286 $highlightedFields = $highlightedRelFields = [];
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 }
303 if (($first === 'a' && $second === 'b') || ($first === 'b' && $second === 'a')) {
304 $cType = $contactRelationCache[$id]["contact_type_{$second}"];
305
306 //CRM-5125 for contact subtype specific relationshiptypes
307 $cSubType = NULL;
308 if (!empty($contactRelationCache[$id]["contact_sub_type_{$second}"])) {
309 $cSubType = $contactRelationCache[$id]["contact_sub_type_{$second}"];
310 }
311
312 if (!$cType) {
313 $cType = 'All';
314 }
315
316 $relatedFields = CRM_Contact_BAO_Contact::importableFields($cType);
317 unset($relatedFields['']);
318 $values = [];
319 foreach ($relatedFields as $name => $field) {
320 $values[$name] = $field['title'];
321 if (isset($hasLocationTypes[$name])) {
322 $sel3[$key][$name] = $this->_location_types;
323 }
324 elseif ($name === 'url') {
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
333 if (empty($this->_formattedFieldNames[$cType]) || $cType == $this->_contactType) {
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
341 if ($this->_onDuplicate != CRM_Import_Parser::DUPLICATE_NOCHECK && !empty($this->_dedupeFields[$cType]) &&
342 is_array($this->_dedupeFields[$cType])
343 ) {
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)';
349 }
350 }
351 $cTypeArray[] = $cType;
352 }
353 }
354
355 foreach ($highlightedFields as $k => $v) {
356 if ($v == $cType || $v === 'All') {
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;
384 if (!empty($hasLocationTypes[$key])) {
385 $options = $this->_location_types;
386 }
387 elseif ($key === 'url') {
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
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'));
404
405 for ($i = 0; $i < $this->_columnCount; $i++) {
406 $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
407
408 if ($this->get('savedMapping')) {
409 list($defaults, $js) = $this->loadSavedMapping($processor, $mappingName, $i, $defaults, $js, $hasColumnNames, $dataPatterns, $columnPatterns);
410 }
411 else {
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;
419 }
420 else {
421 // Infer the default from the column names if we have them
422 $defaults["mapper[$i]"] = [
423 $this->defaultFromColumnName($this->_columnNames[$i],
424 $columnPatterns
425 ),
426 0,
427 ];
428 }
429 }
430 else {
431 // Otherwise guess the default from the form of the data
432 $defaults["mapper[$i]"] = [
433 $this->defaultFromData($dataPatterns, $i),
434 // $defaultLocationType->id
435 0,
436 ];
437 }
438 }
439 $sel->setOptions([$sel1, $sel2, $sel3, $sel4]);
440 }
441
442 $js .= "</script>\n";
443 $this->assign('initHideBoxes', $js);
444
445 //set warning if mismatch in more than
446 if (isset($mappingName) &&
447 ($this->_columnCount != count($mappingName))
448 ) {
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.'));
450 }
451
452 $this->setDefaults($defaults);
453
454 $this->addButtons([
455 [
456 'type' => 'back',
457 'name' => ts('Previous'),
458 ],
459 [
460 'type' => 'next',
461 'name' => ts('Continue'),
462 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
463 'isDefault' => TRUE,
464 ],
465 [
466 'type' => 'cancel',
467 'name' => ts('Cancel'),
468 ],
469 ]);
470 }
471
472 /**
473 * Global validation rules for the form.
474 *
475 * @param array $fields
476 * Posted values of the form.
477 *
478 * @return array
479 * list of errors to be posted back to the form
480 */
481 public static function formRule($fields) {
482 $errors = [];
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');
487 }
488 else {
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');
492 }
493 }
494 }
495 $template = CRM_Core_Smarty::singleton();
496 if (!empty($fields['saveMapping'])) {
497 $template->assign('isCheked', TRUE);
498 }
499
500 if (!empty($errors)) {
501 $_flag = 1;
502 $assignError = new CRM_Core_Page();
503 $assignError->assign('mappingDetailsError', $_flag);
504 return $errors;
505 }
506 else {
507 return TRUE;
508 }
509 }
510
511 /**
512 * Process the mapped fields and map it into the uploaded file.
513 */
514 public function postProcess() {
515 $params = $this->controller->exportValues('MapField');
516
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);
521 return;
522 }
523 $mapperKeys = $this->controller->exportValue($this->_name, 'mapper');
524
525 $parser = $this->submit($params, $mapperKeys);
526
527 // add all the necessary variables to the form
528 $parser->set($this);
529 }
530
531 /**
532 * Format custom field name.
533 *
534 * Combine group and field name to avoid conflict.
535 *
536 * @param array $fields
537 *
538 * @return array
539 */
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;
546 }
547 }
548
549 if (!empty($fieldIds) && is_array($fieldIds)) {
550 $groupTitles = CRM_Core_BAO_CustomGroup::getGroupTitles($fieldIds);
551
552 if (!empty($groupTitles)) {
553 foreach ($groupTitles as $fId => $values) {
554 $key = "custom_{$fId}";
555 $groupTitle = $values['groupTitle'];
556 $formattedFieldNames[$key] = $fields[$key] . ' :: ' . $groupTitle;
557 }
558 }
559 }
560
561 return $formattedFieldNames;
562 }
563
564 /**
565 * Main submit function.
566 *
567 * Extracted to add testing & start refactoring.
568 *
569 * @param $params
570 * @param $mapperKeys
571 *
572 * @return \CRM_Contact_Import_Parser_Contact
573 * @throws \CiviCRM_API3_Exception
574 */
575 public function submit($params, $mapperKeys) {
576 $mapper = $mapperKeysMain = $locations = [];
577 $parserParameters = CRM_Contact_Import_Parser_Contact::getParameterForParser($this->_columnCount);
578
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');
584
585 for ($i = 0; $i < $this->_columnCount; $i++) {
586
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;
593
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];
598 }
599 else {
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];
605 }
606 elseif ($fldName === 'im') {
607 $parserParameters['mapperImProvider'][$i] = $imProviders[$selTwo];
608 }
609 }
610 }
611 }
612
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')
617 ) {
618 $parserParameters['mapperRelated'][$i] = $this->_mapperFields[$fldName];
619 if ($selOne) {
620 if ($selOne === 'url') {
621 $parserParameters['relatedContactWebsiteType'][$i] = $websiteTypes[$selTwo];
622 }
623 else {
624 $parserParameters['relatedContactLocType'][$i] = CRM_Utils_Array::value($selTwo, $locationTypes);
625 if ($selThree) {
626 if ($selOne === 'phone') {
627 $parserParameters['relatedContactPhoneType'][$i] = $phoneTypes[$selThree];
628 }
629 elseif ($selOne === 'im') {
630 $parserParameters['relatedContactImProvider'][$i] = $imProviders[$selThree];
631 }
632 }
633 }
634
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];
641 }
642 }
643 }
644
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);
658
659 // store mapping Id to display it in the preview page
660 $this->set('loadMappingId', CRM_Utils_Array::value('mappingId', $params));
661
662 //Updating Mapping Records
663 if (!empty($params['updateMapping'])) {
664
665 $mappingFields = new CRM_Core_DAO_MappingField();
666 $mappingFields->mapping_id = $params['mappingId'];
667 $mappingFields->find();
668
669 $mappingFieldsId = [];
670 while ($mappingFields->fetch()) {
671 if ($mappingFields->id) {
672 $mappingFieldsId[$mappingFields->column_number] = $mappingFields->id;
673 }
674 }
675
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;
681
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;
694 }
695 else {
696 if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'phone') {
697 $updateMappingFields->phone_type_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : NULL;
698 }
699 elseif (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'im') {
700 $updateMappingFields->im_provider_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : NULL;
701 }
702 $updateMappingFields->location_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL;
703 }
704 }
705 else {
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;
713 }
714 else {
715 if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'phone') {
716 $updateMappingFields->phone_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL;
717 }
718 elseif (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'im') {
719 $updateMappingFields->im_provider_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL;
720 }
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';
724 }
725 }
726 $updateMappingFields->save();
727 }
728 }
729
730 //Saving Mapping Details and Records
731 if (!empty($params['saveMapping'])) {
732 $mappingParams = [
733 'name' => $params['saveMappingName'],
734 'description' => $params['saveMappingDesc'],
735 'mapping_type_id' => 'Import Contact',
736 ];
737
738 $saveMapping = civicrm_api3('Mapping', 'create', $mappingParams);
739
740 $contactType = $this->get('contactType');
741 switch ($contactType) {
742 case CRM_Import_Parser::CONTACT_INDIVIDUAL:
743 $cType = 'Individual';
744 break;
745
746 case CRM_Import_Parser::CONTACT_HOUSEHOLD:
747 $cType = 'Household';
748 break;
749
750 case CRM_Import_Parser::CONTACT_ORGANIZATION:
751 $cType = 'Organization';
752 }
753
754 $mappingID = NULL;
755 for ($i = 0; $i < $this->_columnCount; $i++) {
756 $mappingID = $this->saveMappingField($mapperKeys, $saveMapping, $cType, $i, $mapper, $parserParameters);
757 }
758 $this->set('savedMapping', $mappingID);
759 }
760
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']
766 );
767
768 $primaryKeyName = $this->get('primaryKeyName');
769 $statusFieldName = $this->get('statusFieldName');
770 $parser->run($this->_importTableName,
771 $mapper,
772 CRM_Import_Parser::MODE_PREVIEW,
773 $this->get('contactType'),
774 $primaryKeyName,
775 $statusFieldName,
776 $this->_onDuplicate,
777 NULL, NULL, FALSE,
778 CRM_Contact_Import_Parser::DEFAULT_TIMEOUT,
779 $this->get('contactSubType'),
780 $this->get('dedupe')
781 );
782 return $parser;
783 }
784
785 /**
786 * @param $mapperKeys
787 * @param array $saveMapping
788 * @param string $cType
789 * @param int $i
790 * @param array $mapper
791 * @param array $parserParameters
792 *
793 * @return int
794 */
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;
800
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;
813 }
814 else {
815 if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'phone') {
816 $saveMappingFields->phone_type_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : NULL;
817 }
818 elseif (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'im') {
819 $saveMappingFields->im_provider_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : NULL;
820 }
821 $saveMappingFields->location_type_id = (isset($mapperKeys[$i][2]) && $mapperKeys[$i][2] !== 'Primary') ? $mapperKeys[$i][2] : NULL;
822 }
823 }
824 else {
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;
831 }
832 else {
833 if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'phone') {
834 $saveMappingFields->phone_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL;
835 }
836 elseif (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'im') {
837 $saveMappingFields->im_provider_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL;
838 }
839 $saveMappingFields->location_type_id = is_numeric($locationTypeID) ? $locationTypeID : NULL;
840 }
841 $saveMappingFields->relationship_type_id = NULL;
842 }
843 $saveMappingFields->save();
844 return $saveMappingFields->mapping_id;
845 }
846
847 /**
848 * @param \CRM_Import_ImportProcessor $processor
849 * @param $mappingName
850 * @param int $i
851 * @param array $defaults
852 * @param string $js
853 * @param bool $hasColumnNames
854 * @param array $dataPatterns
855 * @param array $columnPatterns
856 *
857 * @return array
858 * @throws \CiviCRM_API3_Exception
859 */
860 public function loadSavedMapping($processor, $mappingName, $i, $defaults, $js, $hasColumnNames, $dataPatterns, $columnPatterns) {
861 $jsSet = FALSE;
862 $formName = $processor->getFormName();
863 if (isset($mappingName[$i])) {
864 if ($mappingName[$i] != ts('- do not import -')) {
865
866 if ($processor->getRelationshipKey($i)) {
867 $defaults["mapper[$i]"] = $processor->getSavedQuickformDefaultsForColumn($i);
868 $js = $processor->getQuickFormJSForField($i);
869 }
870 else {
871 $defaults["mapper[$i]"] = $processor->getSavedQuickformDefaultsForColumn($i);
872 $js .= $processor->getQuickFormJSForField($i);
873 }
874 }
875 else {
876 $defaults["mapper[$i]"] = [];
877 for ($k = 1; $k < 4; $k++) {
878 $js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
879 }
880 }
881 }
882 else {
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";
885
886 if ($hasColumnNames) {
887 $defaults["mapper[$i]"] = [$this->defaultFromColumnName($this->_columnNames[$i], $columnPatterns)];
888 }
889 else {
890 $defaults["mapper[$i]"] = [$this->defaultFromData($dataPatterns, $i)];
891 }
892 }
893 return [$defaults, $js];
894 }
895
896 }