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