Merge pull request #19057 from ixiam/dev/core#2173
[civicrm-core.git] / CRM / Contact / Import / Parser.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 abstract class CRM_Contact_Import_Parser extends CRM_Import_Parser {
18
19 protected $_tableName;
20
21 /**
22 * Total number of lines in file
23 *
24 * @var int
25 */
26 protected $_rowCount;
27
28 /**
29 * Running total number of un-matched Contacts.
30 *
31 * @var int
32 */
33 protected $_unMatchCount;
34
35 /**
36 * Array of unmatched lines.
37 *
38 * @var array
39 */
40 protected $_unMatch;
41
42 /**
43 * Total number of contacts with unparsed addresses
44 * @var int
45 */
46 protected $_unparsedAddressCount;
47
48 /**
49 * Filename of mismatch data
50 *
51 * @var string
52 */
53 protected $_misMatchFilemName;
54
55 protected $_primaryKeyName;
56 protected $_statusFieldName;
57
58 protected $fieldMetadata = [];
59 /**
60 * On duplicate
61 *
62 * @var int
63 */
64 public $_onDuplicate;
65
66 /**
67 * Dedupe rule group id to use if set
68 *
69 * @var int
70 */
71 public $_dedupeRuleGroupID = NULL;
72
73 /**
74 * Run import.
75 *
76 * @param string $tableName
77 * @param array $mapper
78 * @param int $mode
79 * @param int $contactType
80 * @param string $primaryKeyName
81 * @param string $statusFieldName
82 * @param int $onDuplicate
83 * @param int $statusID
84 * @param int $totalRowCount
85 * @param bool $doGeocodeAddress
86 * @param int $timeout
87 * @param string $contactSubType
88 * @param int $dedupeRuleGroupID
89 *
90 * @return mixed
91 */
92 public function run(
93 $tableName,
94 $mapper = [],
95 $mode = self::MODE_PREVIEW,
96 $contactType = self::CONTACT_INDIVIDUAL,
97 $primaryKeyName = '_id',
98 $statusFieldName = '_status',
99 $onDuplicate = self::DUPLICATE_SKIP,
100 $statusID = NULL,
101 $totalRowCount = NULL,
102 $doGeocodeAddress = FALSE,
103 $timeout = CRM_Contact_Import_Parser::DEFAULT_TIMEOUT,
104 $contactSubType = NULL,
105 $dedupeRuleGroupID = NULL
106 ) {
107
108 // TODO: Make the timeout actually work
109 $this->_onDuplicate = $onDuplicate;
110 $this->_dedupeRuleGroupID = $dedupeRuleGroupID;
111
112 switch ($contactType) {
113 case CRM_Import_Parser::CONTACT_INDIVIDUAL:
114 $this->_contactType = 'Individual';
115 break;
116
117 case CRM_Import_Parser::CONTACT_HOUSEHOLD:
118 $this->_contactType = 'Household';
119 break;
120
121 case CRM_Import_Parser::CONTACT_ORGANIZATION:
122 $this->_contactType = 'Organization';
123 }
124
125 $this->_contactSubType = $contactSubType;
126
127 $this->init();
128
129 $this->_rowCount = $this->_warningCount = 0;
130 $this->_invalidRowCount = $this->_validCount = 0;
131 $this->_totalCount = $this->_conflictCount = 0;
132
133 $this->_errors = [];
134 $this->_warnings = [];
135 $this->_conflicts = [];
136 $this->_unparsedAddresses = [];
137
138 $this->_tableName = $tableName;
139 $this->_primaryKeyName = $primaryKeyName;
140 $this->_statusFieldName = $statusFieldName;
141
142 if ($mode == self::MODE_MAPFIELD) {
143 $this->_rows = [];
144 }
145 else {
146 $this->_activeFieldCount = count($this->_activeFields);
147 }
148
149 if ($mode == self::MODE_IMPORT) {
150 //get the key of email field
151 foreach ($mapper as $key => $value) {
152 if (strtolower($value) == 'email') {
153 $emailKey = $key;
154 break;
155 }
156 }
157 }
158
159 if ($statusID) {
160 $this->progressImport($statusID);
161 $startTimestamp = $currTimestamp = $prevTimestamp = time();
162 }
163 // get the contents of the temp. import table
164 $query = "SELECT * FROM $tableName";
165 if ($mode == self::MODE_IMPORT) {
166 $query .= " WHERE $statusFieldName = 'NEW'";
167 }
168
169 $result = CRM_Core_DAO::executeQuery($query);
170
171 while ($result->fetch()) {
172 $values = array_values($result->toArray());
173 $this->_rowCount++;
174
175 /* trim whitespace around the values */
176 foreach ($values as $k => $v) {
177 $values[$k] = trim($v, " \t\r\n");
178 }
179 if (CRM_Utils_System::isNull($values)) {
180 continue;
181 }
182
183 $this->_totalCount++;
184
185 if ($mode == self::MODE_MAPFIELD) {
186 $returnCode = $this->mapField($values);
187 }
188 elseif ($mode == self::MODE_PREVIEW) {
189 $returnCode = $this->preview($values);
190 }
191 elseif ($mode == self::MODE_SUMMARY) {
192 $returnCode = $this->summary($values);
193 }
194 elseif ($mode == self::MODE_IMPORT) {
195 //print "Running parser in import mode<br/>\n";
196 $returnCode = $this->import($onDuplicate, $values, $doGeocodeAddress);
197 if ($statusID && (($this->_rowCount % 50) == 0)) {
198 $prevTimestamp = $this->progressImport($statusID, FALSE, $startTimestamp, $prevTimestamp, $totalRowCount);
199 }
200 }
201 else {
202 $returnCode = self::ERROR;
203 }
204
205 // note that a line could be valid but still produce a warning
206 if ($returnCode & self::VALID) {
207 $this->_validCount++;
208 if ($mode == self::MODE_MAPFIELD) {
209 $this->_rows[] = $values;
210 $this->_activeFieldCount = max($this->_activeFieldCount, count($values));
211 }
212 }
213
214 if ($returnCode & self::WARNING) {
215 $this->_warningCount++;
216 if ($this->_warningCount < $this->_maxWarningCount) {
217 $this->_warningCount[] = $line;
218 }
219 }
220
221 if ($returnCode & self::ERROR) {
222 $this->_invalidRowCount++;
223 array_unshift($values, $this->_rowCount);
224 $this->_errors[] = $values;
225 }
226
227 if ($returnCode & self::CONFLICT) {
228 $this->_conflictCount++;
229 array_unshift($values, $this->_rowCount);
230 $this->_conflicts[] = $values;
231 }
232
233 if ($returnCode & self::NO_MATCH) {
234 $this->_unMatchCount++;
235 array_unshift($values, $this->_rowCount);
236 $this->_unMatch[] = $values;
237 }
238
239 if ($returnCode & self::DUPLICATE) {
240 if ($returnCode & self::MULTIPLE_DUPE) {
241 /* TODO: multi-dupes should be counted apart from singles
242 * on non-skip action */
243 }
244 $this->_duplicateCount++;
245 array_unshift($values, $this->_rowCount);
246 $this->_duplicates[] = $values;
247 if ($onDuplicate != self::DUPLICATE_SKIP) {
248 $this->_validCount++;
249 }
250 }
251
252 if ($returnCode & self::UNPARSED_ADDRESS_WARNING) {
253 $this->_unparsedAddressCount++;
254 array_unshift($values, $this->_rowCount);
255 $this->_unparsedAddresses[] = $values;
256 }
257 // we give the derived class a way of aborting the process
258 // note that the return code could be multiple code or'ed together
259 if ($returnCode & self::STOP) {
260 break;
261 }
262
263 // if we are done processing the maxNumber of lines, break
264 if ($this->_maxLinesToProcess > 0 && $this->_validCount >= $this->_maxLinesToProcess) {
265 break;
266 }
267
268 // see if we've hit our timeout yet
269 /* if ( $the_thing_with_the_stuff ) {
270 do_something( );
271 } */
272 }
273
274 if ($mode == self::MODE_PREVIEW || $mode == self::MODE_IMPORT) {
275 $customHeaders = $mapper;
276
277 $customfields = CRM_Core_BAO_CustomField::getFields($this->_contactType);
278 foreach ($customHeaders as $key => $value) {
279 if ($id = CRM_Core_BAO_CustomField::getKeyID($value)) {
280 $customHeaders[$key] = $customfields[$id][0];
281 }
282 }
283
284 if ($this->_invalidRowCount) {
285 // removed view url for invlaid contacts
286 $headers = array_merge([
287 ts('Line Number'),
288 ts('Reason'),
289 ], $customHeaders);
290 $this->_errorFileName = self::errorFileName(self::ERROR);
291 self::exportCSV($this->_errorFileName, $headers, $this->_errors);
292 }
293 if ($this->_conflictCount) {
294 $headers = array_merge([
295 ts('Line Number'),
296 ts('Reason'),
297 ], $customHeaders);
298 $this->_conflictFileName = self::errorFileName(self::CONFLICT);
299 self::exportCSV($this->_conflictFileName, $headers, $this->_conflicts);
300 }
301 if ($this->_duplicateCount) {
302 $headers = array_merge([
303 ts('Line Number'),
304 ts('View Contact URL'),
305 ], $customHeaders);
306
307 $this->_duplicateFileName = self::errorFileName(self::DUPLICATE);
308 self::exportCSV($this->_duplicateFileName, $headers, $this->_duplicates);
309 }
310 if ($this->_unMatchCount) {
311 $headers = array_merge([
312 ts('Line Number'),
313 ts('Reason'),
314 ], $customHeaders);
315
316 $this->_misMatchFilemName = self::errorFileName(self::NO_MATCH);
317 self::exportCSV($this->_misMatchFilemName, $headers, $this->_unMatch);
318 }
319 if ($this->_unparsedAddressCount) {
320 $headers = array_merge([
321 ts('Line Number'),
322 ts('Contact Edit URL'),
323 ], $customHeaders);
324 $this->_errorFileName = self::errorFileName(self::UNPARSED_ADDRESS_WARNING);
325 self::exportCSV($this->_errorFileName, $headers, $this->_unparsedAddresses);
326 }
327 }
328 //echo "$this->_totalCount,$this->_invalidRowCount,$this->_conflictCount,$this->_duplicateCount";
329 return $this->fini();
330 }
331
332 /**
333 * Given a list of the importable field keys that the user has selected.
334 * set the active fields array to this list
335 *
336 * @param array $fieldKeys
337 * Mapped array of values.
338 */
339 public function setActiveFields($fieldKeys) {
340 $this->_activeFieldCount = count($fieldKeys);
341 foreach ($fieldKeys as $key) {
342 if (empty($this->_fields[$key])) {
343 $this->_activeFields[] = new CRM_Contact_Import_Field('', ts('- do not import -'));
344 }
345 else {
346 $this->_activeFields[] = clone($this->_fields[$key]);
347 }
348 }
349 }
350
351 /**
352 * @param $elements
353 */
354 public function setActiveFieldLocationTypes($elements) {
355 for ($i = 0; $i < count($elements); $i++) {
356 $this->_activeFields[$i]->_hasLocationType = $elements[$i];
357 }
358 }
359
360 /**
361 * @param $elements
362 */
363
364 /**
365 * @param $elements
366 */
367 public function setActiveFieldPhoneTypes($elements) {
368 for ($i = 0; $i < count($elements); $i++) {
369 $this->_activeFields[$i]->_phoneType = $elements[$i];
370 }
371 }
372
373 /**
374 * @param $elements
375 */
376 public function setActiveFieldWebsiteTypes($elements) {
377 for ($i = 0; $i < count($elements); $i++) {
378 $this->_activeFields[$i]->_websiteType = $elements[$i];
379 }
380 }
381
382 /**
383 * Set IM Service Provider type fields.
384 *
385 * @param array $elements
386 * IM service provider type ids.
387 */
388 public function setActiveFieldImProviders($elements) {
389 for ($i = 0; $i < count($elements); $i++) {
390 $this->_activeFields[$i]->_imProvider = $elements[$i];
391 }
392 }
393
394 /**
395 * @param $elements
396 */
397 public function setActiveFieldRelated($elements) {
398 for ($i = 0; $i < count($elements); $i++) {
399 $this->_activeFields[$i]->_related = $elements[$i];
400 }
401 }
402
403 /**
404 * @param $elements
405 */
406 public function setActiveFieldRelatedContactType($elements) {
407 for ($i = 0; $i < count($elements); $i++) {
408 $this->_activeFields[$i]->_relatedContactType = $elements[$i];
409 }
410 }
411
412 /**
413 * @param $elements
414 */
415 public function setActiveFieldRelatedContactDetails($elements) {
416 for ($i = 0; $i < count($elements); $i++) {
417 $this->_activeFields[$i]->_relatedContactDetails = $elements[$i];
418 }
419 }
420
421 /**
422 * @param $elements
423 */
424 public function setActiveFieldRelatedContactLocType($elements) {
425 for ($i = 0; $i < count($elements); $i++) {
426 $this->_activeFields[$i]->_relatedContactLocType = $elements[$i];
427 }
428 }
429
430 /**
431 * Set active field for related contact's phone type.
432 *
433 * @param array $elements
434 */
435 public function setActiveFieldRelatedContactPhoneType($elements) {
436 for ($i = 0; $i < count($elements); $i++) {
437 $this->_activeFields[$i]->_relatedContactPhoneType = $elements[$i];
438 }
439 }
440
441 /**
442 * @param $elements
443 */
444 public function setActiveFieldRelatedContactWebsiteType($elements) {
445 for ($i = 0; $i < count($elements); $i++) {
446 $this->_activeFields[$i]->_relatedContactWebsiteType = $elements[$i];
447 }
448 }
449
450 /**
451 * Set IM Service Provider type fields for related contacts.
452 *
453 * @param array $elements
454 * IM service provider type ids of related contact.
455 */
456 public function setActiveFieldRelatedContactImProvider($elements) {
457 for ($i = 0; $i < count($elements); $i++) {
458 $this->_activeFields[$i]->_relatedContactImProvider = $elements[$i];
459 }
460 }
461
462 /**
463 * Format the field values for input to the api.
464 *
465 * @return array
466 * (reference ) associative array of name/value pairs
467 */
468 public function &getActiveFieldParams() {
469 $params = [];
470
471 for ($i = 0; $i < $this->_activeFieldCount; $i++) {
472 if ($this->_activeFields[$i]->_name == 'do_not_import') {
473 continue;
474 }
475
476 if (isset($this->_activeFields[$i]->_value)) {
477 if (isset($this->_activeFields[$i]->_hasLocationType)) {
478 if (!isset($params[$this->_activeFields[$i]->_name])) {
479 $params[$this->_activeFields[$i]->_name] = [];
480 }
481
482 $value = [
483 $this->_activeFields[$i]->_name => $this->_activeFields[$i]->_value,
484 'location_type_id' => $this->_activeFields[$i]->_hasLocationType,
485 ];
486
487 if (isset($this->_activeFields[$i]->_phoneType)) {
488 $value['phone_type_id'] = $this->_activeFields[$i]->_phoneType;
489 }
490
491 // get IM service Provider type id
492 if (isset($this->_activeFields[$i]->_imProvider)) {
493 $value['provider_id'] = $this->_activeFields[$i]->_imProvider;
494 }
495
496 $params[$this->_activeFields[$i]->_name][] = $value;
497 }
498 elseif (isset($this->_activeFields[$i]->_websiteType)) {
499 $value = [
500 $this->_activeFields[$i]->_name => $this->_activeFields[$i]->_value,
501 'website_type_id' => $this->_activeFields[$i]->_websiteType,
502 ];
503
504 $params[$this->_activeFields[$i]->_name][] = $value;
505 }
506
507 if (!isset($params[$this->_activeFields[$i]->_name])) {
508 if (!isset($this->_activeFields[$i]->_related)) {
509 $params[$this->_activeFields[$i]->_name] = $this->_activeFields[$i]->_value;
510 }
511 }
512
513 //minor fix for CRM-4062
514 if (isset($this->_activeFields[$i]->_related)) {
515 if (!isset($params[$this->_activeFields[$i]->_related])) {
516 $params[$this->_activeFields[$i]->_related] = [];
517 }
518
519 if (!isset($params[$this->_activeFields[$i]->_related]['contact_type']) && !empty($this->_activeFields[$i]->_relatedContactType)) {
520 $params[$this->_activeFields[$i]->_related]['contact_type'] = $this->_activeFields[$i]->_relatedContactType;
521 }
522
523 if (isset($this->_activeFields[$i]->_relatedContactLocType) && !empty($this->_activeFields[$i]->_value)) {
524 if (!empty($params[$this->_activeFields[$i]->_related][$this->_activeFields[$i]->_relatedContactDetails]) &&
525 !is_array($params[$this->_activeFields[$i]->_related][$this->_activeFields[$i]->_relatedContactDetails])
526 ) {
527 $params[$this->_activeFields[$i]->_related][$this->_activeFields[$i]->_relatedContactDetails] = [];
528 }
529 $value = [
530 $this->_activeFields[$i]->_relatedContactDetails => $this->_activeFields[$i]->_value,
531 'location_type_id' => $this->_activeFields[$i]->_relatedContactLocType,
532 ];
533
534 if (isset($this->_activeFields[$i]->_relatedContactPhoneType)) {
535 $value['phone_type_id'] = $this->_activeFields[$i]->_relatedContactPhoneType;
536 }
537
538 // get IM service Provider type id for related contact
539 if (isset($this->_activeFields[$i]->_relatedContactImProvider)) {
540 $value['provider_id'] = $this->_activeFields[$i]->_relatedContactImProvider;
541 }
542
543 $params[$this->_activeFields[$i]->_related][$this->_activeFields[$i]->_relatedContactDetails][] = $value;
544 }
545 elseif (isset($this->_activeFields[$i]->_relatedContactWebsiteType)) {
546 $params[$this->_activeFields[$i]->_related][$this->_activeFields[$i]->_relatedContactDetails][] = [
547 'url' => $this->_activeFields[$i]->_value,
548 'website_type_id' => $this->_activeFields[$i]->_relatedContactWebsiteType,
549 ];
550 }
551 elseif (empty($this->_activeFields[$i]->_value) && isset($this->_activeFields[$i]->_relatedContactLocType)) {
552 if (empty($params[$this->_activeFields[$i]->_related][$this->_activeFields[$i]->_relatedContactDetails])) {
553 $params[$this->_activeFields[$i]->_related][$this->_activeFields[$i]->_relatedContactDetails] = [];
554 }
555 }
556 else {
557 $params[$this->_activeFields[$i]->_related][$this->_activeFields[$i]->_relatedContactDetails] = $this->_activeFields[$i]->_value;
558 }
559 }
560 }
561 }
562
563 return $params;
564 }
565
566 /**
567 * @param string $name
568 * @param $title
569 * @param int $type
570 * @param string $headerPattern
571 * @param string $dataPattern
572 * @param bool $hasLocationType
573 */
574 public function addField(
575 $name, $title, $type = CRM_Utils_Type::T_INT,
576 $headerPattern = '//', $dataPattern = '//',
577 $hasLocationType = FALSE
578 ) {
579 $this->_fields[$name] = new CRM_Contact_Import_Field($name, $title, $type, $headerPattern, $dataPattern, $hasLocationType);
580 if (empty($name)) {
581 $this->_fields['doNotImport'] = new CRM_Contact_Import_Field($name, $title, $type, $headerPattern, $dataPattern, $hasLocationType);
582 }
583 }
584
585 /**
586 * Store parser values.
587 *
588 * @param CRM_Core_Session $store
589 *
590 * @param int $mode
591 */
592 public function set($store, $mode = self::MODE_SUMMARY) {
593 $store->set('rowCount', $this->_rowCount);
594 $store->set('fields', $this->getSelectValues());
595 $store->set('fieldTypes', $this->getSelectTypes());
596
597 $store->set('columnCount', $this->_activeFieldCount);
598
599 $store->set('totalRowCount', $this->_totalCount);
600 $store->set('validRowCount', $this->_validCount);
601 $store->set('invalidRowCount', $this->_invalidRowCount);
602 $store->set('conflictRowCount', $this->_conflictCount);
603 $store->set('unMatchCount', $this->_unMatchCount);
604
605 switch ($this->_contactType) {
606 case 'Individual':
607 $store->set('contactType', CRM_Import_Parser::CONTACT_INDIVIDUAL);
608 break;
609
610 case 'Household':
611 $store->set('contactType', CRM_Import_Parser::CONTACT_HOUSEHOLD);
612 break;
613
614 case 'Organization':
615 $store->set('contactType', CRM_Import_Parser::CONTACT_ORGANIZATION);
616 }
617
618 if ($this->_invalidRowCount) {
619 $store->set('errorsFileName', $this->_errorFileName);
620 }
621 if ($this->_conflictCount) {
622 $store->set('conflictsFileName', $this->_conflictFileName);
623 }
624 if (isset($this->_rows) && !empty($this->_rows)) {
625 $store->set('dataValues', $this->_rows);
626 }
627
628 if ($this->_unMatchCount) {
629 $store->set('mismatchFileName', $this->_misMatchFilemName);
630 }
631
632 if ($mode == self::MODE_IMPORT) {
633 $store->set('duplicateRowCount', $this->_duplicateCount);
634 $store->set('unparsedAddressCount', $this->_unparsedAddressCount);
635 if ($this->_duplicateCount) {
636 $store->set('duplicatesFileName', $this->_duplicateFileName);
637 }
638 if ($this->_unparsedAddressCount) {
639 $store->set('errorsFileName', $this->_errorFileName);
640 }
641 }
642 //echo "$this->_totalCount,$this->_invalidRowCount,$this->_conflictCount,$this->_duplicateCount";
643 }
644
645 /**
646 * Export data to a CSV file.
647 *
648 * @param string $fileName
649 * @param array $header
650 * @param array $data
651 */
652 public static function exportCSV($fileName, $header, $data) {
653
654 if (file_exists($fileName) && !is_writable($fileName)) {
655 CRM_Core_Error::movedSiteError($fileName);
656 }
657 //hack to remove '_status', '_statusMsg' and '_id' from error file
658 $errorValues = [];
659 $dbRecordStatus = ['IMPORTED', 'ERROR', 'DUPLICATE', 'INVALID', 'NEW'];
660 foreach ($data as $rowCount => $rowValues) {
661 $count = 0;
662 foreach ($rowValues as $key => $val) {
663 if (in_array($val, $dbRecordStatus) && $count == (count($rowValues) - 3)) {
664 break;
665 }
666 $errorValues[$rowCount][$key] = $val;
667 $count++;
668 }
669 }
670 $data = $errorValues;
671
672 $output = [];
673 $fd = fopen($fileName, 'w');
674
675 foreach ($header as $key => $value) {
676 $header[$key] = "\"$value\"";
677 }
678 $config = CRM_Core_Config::singleton();
679 $output[] = implode($config->fieldSeparator, $header);
680
681 foreach ($data as $datum) {
682 foreach ($datum as $key => $value) {
683 $datum[$key] = "\"$value\"";
684 }
685 $output[] = implode($config->fieldSeparator, $datum);
686 }
687 fwrite($fd, implode("\n", $output));
688 fclose($fd);
689 }
690
691 /**
692 * Update the record with PK $id in the import database table.
693 *
694 * @param int $id
695 * @param array $params
696 */
697 public function updateImportRecord($id, &$params) {
698 $statusFieldName = $this->_statusFieldName;
699 $primaryKeyName = $this->_primaryKeyName;
700
701 if ($statusFieldName && $primaryKeyName) {
702 $dao = new CRM_Core_DAO();
703 $db = $dao->getDatabaseConnection();
704
705 $query = "UPDATE $this->_tableName
706 SET $statusFieldName = ?,
707 ${statusFieldName}Msg = ?
708 WHERE $primaryKeyName = ?";
709 $args = [
710 $params[$statusFieldName],
711 CRM_Utils_Array::value("${statusFieldName}Msg", $params),
712 $id,
713 ];
714
715 //print "Running query: $query<br/>With arguments: ".$params[$statusFieldName].", ".$params["${statusFieldName}Msg"].", $id<br/>";
716
717 $db->query($query, $args);
718 }
719 }
720
721 /**
722 * Format common params data to proper format to store.
723 *
724 * @param array $params
725 * Contain record values.
726 * @param array $formatted
727 * Array of formatted data.
728 * @param array $contactFields
729 * Contact DAO fields.
730 */
731 public function formatCommonData($params, &$formatted, &$contactFields) {
732 $csType = [
733 CRM_Utils_Array::value('contact_type', $formatted),
734 ];
735
736 //CRM-5125
737 //add custom fields for contact sub type
738 if (!empty($this->_contactSubType)) {
739 $csType = $this->_contactSubType;
740 }
741
742 if ($relCsType = CRM_Utils_Array::value('contact_sub_type', $formatted)) {
743 $csType = $relCsType;
744 }
745
746 $customFields = CRM_Core_BAO_CustomField::getFields($formatted['contact_type'], FALSE, FALSE, $csType);
747
748 $addressCustomFields = CRM_Core_BAO_CustomField::getFields('Address');
749 $customFields = $customFields + $addressCustomFields;
750
751 //if a Custom Email Greeting, Custom Postal Greeting or Custom Addressee is mapped, and no "Greeting / Addressee Type ID" is provided, then automatically set the type = Customized, CRM-4575
752 $elements = [
753 'email_greeting_custom' => 'email_greeting',
754 'postal_greeting_custom' => 'postal_greeting',
755 'addressee_custom' => 'addressee',
756 ];
757 foreach ($elements as $k => $v) {
758 if (array_key_exists($k, $params) && !(array_key_exists($v, $params))) {
759 $label = key(CRM_Core_OptionGroup::values($v, TRUE, NULL, NULL, 'AND v.name = "Customized"'));
760 $params[$v] = $label;
761 }
762 }
763
764 //format date first
765 $session = CRM_Core_Session::singleton();
766 $dateType = $session->get("dateTypes");
767 foreach ($params as $key => $val) {
768 $customFieldID = CRM_Core_BAO_CustomField::getKeyID($key);
769 if ($customFieldID &&
770 !array_key_exists($customFieldID, $addressCustomFields)
771 ) {
772 //we should not update Date to null, CRM-4062
773 if ($val && ($customFields[$customFieldID]['data_type'] == 'Date')) {
774 //CRM-21267
775 CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
776 }
777 elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
778 if (empty($val) && !is_numeric($val) && $this->_onDuplicate == CRM_Import_Parser::DUPLICATE_FILL) {
779 //retain earlier value when Import mode is `Fill`
780 unset($params[$key]);
781 }
782 else {
783 $params[$key] = CRM_Utils_String::strtoboolstr($val);
784 }
785 }
786 }
787
788 if ($key == 'birth_date' && $val) {
789 CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
790 }
791 elseif ($key == 'deceased_date' && $val) {
792 CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
793 $params['is_deceased'] = 1;
794 }
795 elseif ($key == 'is_deceased' && $val) {
796 $params[$key] = CRM_Utils_String::strtoboolstr($val);
797 }
798 }
799
800 //now format custom data.
801 foreach ($params as $key => $field) {
802 if (is_array($field)) {
803 $isAddressCustomField = FALSE;
804 foreach ($field as $value) {
805 $break = FALSE;
806 if (is_array($value)) {
807 foreach ($value as $name => $testForEmpty) {
808 if ($addressCustomFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
809 $isAddressCustomField = TRUE;
810 break;
811 }
812 // check if $value does not contain IM provider or phoneType
813 if (($name !== 'phone_type_id' || $name !== 'provider_id') && ($testForEmpty === '' || $testForEmpty == NULL)) {
814 $break = TRUE;
815 break;
816 }
817 }
818 }
819 else {
820 $break = TRUE;
821 }
822
823 if (!$break) {
824 if (!empty($value['location_type_id'])) {
825 $this->formatLocationBlock($value, $formatted);
826 }
827 else {
828 // @todo - this is still reachable - e.g. import with related contact info like firstname,lastname,spouse-first-name,spouse-last-name,spouse-home-phone
829 CRM_Core_Error::deprecatedFunctionWarning('this is not expected to be reachable now');
830 $this->formatContactParameters($value, $formatted);
831 }
832 }
833 }
834 if (!$isAddressCustomField) {
835 continue;
836 }
837 }
838
839 $formatValues = [
840 $key => $field,
841 ];
842
843 if (($key !== 'preferred_communication_method') && (array_key_exists($key, $contactFields))) {
844 // due to merging of individual table and
845 // contact table, we need to avoid
846 // preferred_communication_method forcefully
847 $formatValues['contact_type'] = $formatted['contact_type'];
848 }
849
850 if ($key == 'id' && isset($field)) {
851 $formatted[$key] = $field;
852 }
853 $this->formatContactParameters($formatValues, $formatted);
854
855 //Handling Custom Data
856 // note: Address custom fields will be handled separately inside formatContactParameters
857 if (($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) &&
858 array_key_exists($customFieldID, $customFields) &&
859 !array_key_exists($customFieldID, $addressCustomFields)
860 ) {
861
862 $extends = $customFields[$customFieldID]['extends'] ?? NULL;
863 $htmlType = $customFields[$customFieldID]['html_type'] ?? NULL;
864 $dataType = $customFields[$customFieldID]['data_type'] ?? NULL;
865 $serialized = CRM_Core_BAO_CustomField::isSerialized($customFields[$customFieldID]);
866
867 if (!$serialized && in_array($htmlType, ['Select', 'Radio', 'Autocomplete-Select']) && in_array($dataType, ['String', 'Int'])) {
868 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
869 foreach ($customOption as $customValue) {
870 $val = $customValue['value'] ?? NULL;
871 $label = strtolower($customValue['label'] ?? '');
872 $value = strtolower(trim($formatted[$key]));
873 if (($value == $label) || ($value == strtolower($val))) {
874 $params[$key] = $formatted[$key] = $val;
875 }
876 }
877 }
878 elseif ($serialized && !empty($formatted[$key]) && !empty($params[$key])) {
879 $mulValues = explode(',', $formatted[$key]);
880 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
881 $formatted[$key] = [];
882 $params[$key] = [];
883 foreach ($mulValues as $v1) {
884 foreach ($customOption as $v2) {
885 if ((strtolower($v2['label']) == strtolower(trim($v1))) ||
886 (strtolower($v2['value']) == strtolower(trim($v1)))
887 ) {
888 if ($htmlType == 'CheckBox') {
889 $params[$key][$v2['value']] = $formatted[$key][$v2['value']] = 1;
890 }
891 else {
892 $params[$key][] = $formatted[$key][] = $v2['value'];
893 }
894 }
895 }
896 }
897 }
898 }
899 }
900
901 if (!empty($key) && ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) && array_key_exists($customFieldID, $customFields) &&
902 !array_key_exists($customFieldID, $addressCustomFields)
903 ) {
904 // @todo calling api functions directly is not supported
905 _civicrm_api3_custom_format_params($params, $formatted, $extends);
906 }
907
908 // to check if not update mode and unset the fields with empty value.
909 if (!$this->_updateWithId && array_key_exists('custom', $formatted)) {
910 foreach ($formatted['custom'] as $customKey => $customvalue) {
911 if (empty($formatted['custom'][$customKey][-1]['is_required'])) {
912 $formatted['custom'][$customKey][-1]['is_required'] = $customFields[$customKey]['is_required'];
913 }
914 $emptyValue = $customvalue[-1]['value'] ?? NULL;
915 if (!isset($emptyValue)) {
916 unset($formatted['custom'][$customKey]);
917 }
918 }
919 }
920
921 // parse street address, CRM-5450
922 if ($this->_parseStreetAddress) {
923 if (array_key_exists('address', $formatted) && is_array($formatted['address'])) {
924 foreach ($formatted['address'] as $instance => & $address) {
925 $streetAddress = $address['street_address'] ?? NULL;
926 if (empty($streetAddress)) {
927 continue;
928 }
929 // parse address field.
930 $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($streetAddress);
931
932 //street address consider to be parsed properly,
933 //If we get street_name and street_number.
934 if (empty($parsedFields['street_name']) || empty($parsedFields['street_number'])) {
935 $parsedFields = array_fill_keys(array_keys($parsedFields), '');
936 }
937
938 // merge parse address w/ main address block.
939 $address = array_merge($address, $parsedFields);
940 }
941 }
942 }
943 }
944
945 /**
946 * Format contact parameters.
947 *
948 * @todo this function needs re-writing & re-merging into the main function.
949 *
950 * Here be dragons.
951 *
952 * @param array $values
953 * @param array $params
954 *
955 * @return bool
956 */
957 protected function formatContactParameters(&$values, &$params) {
958 // Crawl through the possible classes:
959 // Contact
960 // Individual
961 // Household
962 // Organization
963 // Location
964 // Address
965 // Email
966 // Phone
967 // IM
968 // Note
969 // Custom
970
971 // first add core contact values since for other Civi modules they are not added
972 $contactFields = CRM_Contact_DAO_Contact::fields();
973 _civicrm_api3_store_values($contactFields, $values, $params);
974
975 if (isset($values['contact_type'])) {
976 // we're an individual/household/org property
977
978 $fields[$values['contact_type']] = CRM_Contact_DAO_Contact::fields();
979
980 _civicrm_api3_store_values($fields[$values['contact_type']], $values, $params);
981 return TRUE;
982 }
983
984 // Cache the various object fields
985 // @todo - remove this after confirming this is just a compilation of other-wise-cached fields.
986 static $fields = [];
987
988 if (isset($values['individual_prefix'])) {
989 if (!empty($params['prefix_id'])) {
990 $prefixes = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id');
991 $params['prefix'] = $prefixes[$params['prefix_id']];
992 }
993 else {
994 $params['prefix'] = $values['individual_prefix'];
995 }
996 return TRUE;
997 }
998
999 if (isset($values['individual_suffix'])) {
1000 if (!empty($params['suffix_id'])) {
1001 $suffixes = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id');
1002 $params['suffix'] = $suffixes[$params['suffix_id']];
1003 }
1004 else {
1005 $params['suffix'] = $values['individual_suffix'];
1006 }
1007 return TRUE;
1008 }
1009
1010 // CRM-4575
1011 if (isset($values['email_greeting'])) {
1012 if (!empty($params['email_greeting_id'])) {
1013 $emailGreetingFilter = [
1014 'contact_type' => $params['contact_type'] ?? NULL,
1015 'greeting_type' => 'email_greeting',
1016 ];
1017 $emailGreetings = CRM_Core_PseudoConstant::greeting($emailGreetingFilter);
1018 $params['email_greeting'] = $emailGreetings[$params['email_greeting_id']];
1019 }
1020 else {
1021 $params['email_greeting'] = $values['email_greeting'];
1022 }
1023
1024 return TRUE;
1025 }
1026
1027 if (isset($values['postal_greeting'])) {
1028 if (!empty($params['postal_greeting_id'])) {
1029 $postalGreetingFilter = [
1030 'contact_type' => $params['contact_type'] ?? NULL,
1031 'greeting_type' => 'postal_greeting',
1032 ];
1033 $postalGreetings = CRM_Core_PseudoConstant::greeting($postalGreetingFilter);
1034 $params['postal_greeting'] = $postalGreetings[$params['postal_greeting_id']];
1035 }
1036 else {
1037 $params['postal_greeting'] = $values['postal_greeting'];
1038 }
1039 return TRUE;
1040 }
1041
1042 if (isset($values['addressee'])) {
1043 $params['addressee'] = $values['addressee'];
1044 return TRUE;
1045 }
1046
1047 if (isset($values['gender'])) {
1048 if (!empty($params['gender_id'])) {
1049 $genders = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
1050 $params['gender'] = $genders[$params['gender_id']];
1051 }
1052 else {
1053 $params['gender'] = $values['gender'];
1054 }
1055 return TRUE;
1056 }
1057
1058 if (!empty($values['preferred_communication_method'])) {
1059 $comm = [];
1060 $pcm = array_change_key_case(array_flip(CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method')), CASE_LOWER);
1061
1062 $preffComm = explode(',', $values['preferred_communication_method']);
1063 foreach ($preffComm as $v) {
1064 $v = strtolower(trim($v));
1065 if (array_key_exists($v, $pcm)) {
1066 $comm[$pcm[$v]] = 1;
1067 }
1068 }
1069
1070 $params['preferred_communication_method'] = $comm;
1071 return TRUE;
1072 }
1073
1074 // format the website params.
1075 if (!empty($values['url'])) {
1076 static $websiteFields;
1077 if (!is_array($websiteFields)) {
1078 $websiteFields = CRM_Core_DAO_Website::fields();
1079 }
1080 if (!array_key_exists('website', $params) ||
1081 !is_array($params['website'])
1082 ) {
1083 $params['website'] = [];
1084 }
1085
1086 $websiteCount = count($params['website']);
1087 _civicrm_api3_store_values($websiteFields, $values,
1088 $params['website'][++$websiteCount]
1089 );
1090
1091 return TRUE;
1092 }
1093
1094 if (isset($values['note'])) {
1095 // add a note field
1096 if (!isset($params['note'])) {
1097 $params['note'] = [];
1098 }
1099 $noteBlock = count($params['note']) + 1;
1100
1101 $params['note'][$noteBlock] = [];
1102 if (!isset($fields['Note'])) {
1103 $fields['Note'] = CRM_Core_DAO_Note::fields();
1104 }
1105
1106 // get the current logged in civicrm user
1107 $session = CRM_Core_Session::singleton();
1108 $userID = $session->get('userID');
1109
1110 if ($userID) {
1111 $values['contact_id'] = $userID;
1112 }
1113
1114 _civicrm_api3_store_values($fields['Note'], $values, $params['note'][$noteBlock]);
1115
1116 return TRUE;
1117 }
1118
1119 // Check for custom field values
1120 $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $values),
1121 FALSE, FALSE, NULL, NULL, FALSE, FALSE, FALSE
1122 );
1123
1124 foreach ($values as $key => $value) {
1125 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
1126 // check if it's a valid custom field id
1127
1128 if (!array_key_exists($customFieldID, $customFields)) {
1129 return civicrm_api3_create_error('Invalid custom field ID');
1130 }
1131 else {
1132 $params[$key] = $value;
1133 }
1134 }
1135 }
1136 return TRUE;
1137 }
1138
1139 /**
1140 * Format location block ready for importing.
1141 *
1142 * There is some test coverage for this in CRM_Contact_Import_Parser_ContactTest
1143 * e.g. testImportPrimaryAddress.
1144 *
1145 * @param array $values
1146 * @param array $params
1147 *
1148 * @return bool
1149 */
1150 protected function formatLocationBlock(&$values, &$params) {
1151 $blockTypes = [
1152 'phone' => 'Phone',
1153 'email' => 'Email',
1154 'im' => 'IM',
1155 'openid' => 'OpenID',
1156 'phone_ext' => 'Phone',
1157 ];
1158 foreach ($blockTypes as $blockFieldName => $block) {
1159 if (!array_key_exists($blockFieldName, $values)) {
1160 continue;
1161 }
1162 $blockIndex = $values['location_type_id'] . (!empty($values['phone_type_id']) ? '_' . $values['phone_type_id'] : '');
1163
1164 // block present in value array.
1165 if (!array_key_exists($blockFieldName, $params) || !is_array($params[$blockFieldName])) {
1166 $params[$blockFieldName] = [];
1167 }
1168
1169 $fields[$block] = $this->getMetadataForEntity($block);
1170
1171 // copy value to dao field name.
1172 if ($blockFieldName == 'im') {
1173 $values['name'] = $values[$blockFieldName];
1174 }
1175
1176 _civicrm_api3_store_values($fields[$block], $values,
1177 $params[$blockFieldName][$blockIndex]
1178 );
1179
1180 $this->fillPrimary($params[$blockFieldName][$blockIndex], $values, $block, CRM_Utils_Array::value('id', $params));
1181
1182 if (empty($params['id']) && (count($params[$blockFieldName]) == 1)) {
1183 $params[$blockFieldName][$blockIndex]['is_primary'] = TRUE;
1184 }
1185
1186 // we only process single block at a time.
1187 return TRUE;
1188 }
1189
1190 // handle address fields.
1191 if (!array_key_exists('address', $params) || !is_array($params['address'])) {
1192 $params['address'] = [];
1193 }
1194
1195 // Note: we doing multiple value formatting here for address custom fields, plus putting into right format.
1196 // The actual formatting (like date, country ..etc) for address custom fields is taken care of while saving
1197 // the address in CRM_Core_BAO_Address::create method
1198 if (!empty($values['location_type_id'])) {
1199 static $customFields = [];
1200 if (empty($customFields)) {
1201 $customFields = CRM_Core_BAO_CustomField::getFields('Address');
1202 }
1203 // make a copy of values, as we going to make changes
1204 $newValues = $values;
1205 foreach ($values as $key => $val) {
1206 $customFieldID = CRM_Core_BAO_CustomField::getKeyID($key);
1207 if ($customFieldID && array_key_exists($customFieldID, $customFields)) {
1208
1209 $htmlType = $customFields[$customFieldID]['html_type'] ?? NULL;
1210 if (CRM_Core_BAO_CustomField::isSerialized($customFields[$customFieldID]) && $val) {
1211 $mulValues = explode(',', $val);
1212 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
1213 $newValues[$key] = [];
1214 foreach ($mulValues as $v1) {
1215 foreach ($customOption as $v2) {
1216 if ((strtolower($v2['label']) == strtolower(trim($v1))) ||
1217 (strtolower($v2['value']) == strtolower(trim($v1)))
1218 ) {
1219 if ($htmlType == 'CheckBox') {
1220 $newValues[$key][$v2['value']] = 1;
1221 }
1222 else {
1223 $newValues[$key][] = $v2['value'];
1224 }
1225 }
1226 }
1227 }
1228 }
1229 }
1230 }
1231 // consider new values
1232 $values = $newValues;
1233 }
1234
1235 $fields['Address'] = $this->getMetadataForEntity('Address');
1236 // @todo this is kinda replicated below....
1237 _civicrm_api3_store_values($fields['Address'], $values, $params['address'][$values['location_type_id']]);
1238
1239 $addressFields = [
1240 'county',
1241 'country',
1242 'state_province',
1243 'supplemental_address_1',
1244 'supplemental_address_2',
1245 'supplemental_address_3',
1246 'StateProvince.name',
1247 ];
1248 foreach (array_keys($customFields) as $customFieldID) {
1249 $addressFields[] = 'custom_' . $customFieldID;
1250 }
1251
1252 foreach ($addressFields as $field) {
1253 if (array_key_exists($field, $values)) {
1254 if (!array_key_exists('address', $params)) {
1255 $params['address'] = [];
1256 }
1257 $params['address'][$values['location_type_id']][$field] = $values[$field];
1258 }
1259 }
1260
1261 $this->fillPrimary($params['address'][$values['location_type_id']], $values, 'address', CRM_Utils_Array::value('id', $params));
1262 return TRUE;
1263 }
1264
1265 /**
1266 * Get the field metadata for the relevant entity.
1267 *
1268 * @param string $entity
1269 *
1270 * @return array
1271 */
1272 protected function getMetadataForEntity($entity) {
1273 if (!isset($this->fieldMetadata[$entity])) {
1274 $className = "CRM_Core_DAO_$entity";
1275 $this->fieldMetadata[$entity] = $className::fields();
1276 }
1277 return $this->fieldMetadata[$entity];
1278 }
1279
1280 /**
1281 * Fill in the primary location.
1282 *
1283 * If the contact has a primary address we update it. Otherwise
1284 * we add an address of the default location type.
1285 *
1286 * @param array $params
1287 * Address block parameters
1288 * @param array $values
1289 * Input values
1290 * @param string $entity
1291 * - address, email, phone
1292 * @param int|null $contactID
1293 *
1294 * @throws \CiviCRM_API3_Exception
1295 */
1296 protected function fillPrimary(&$params, $values, $entity, $contactID) {
1297 if ($values['location_type_id'] === 'Primary') {
1298 if ($contactID) {
1299 $primary = civicrm_api3($entity, 'get', [
1300 'return' => 'location_type_id',
1301 'contact_id' => $contactID,
1302 'is_primary' => 1,
1303 'sequential' => 1,
1304 ]);
1305 }
1306 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
1307 $params['location_type_id'] = (int) (isset($primary) && $primary['count']) ? $primary['values'][0]['location_type_id'] : $defaultLocationType->id;
1308 $params['is_primary'] = 1;
1309 }
1310 }
1311
1312 }