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