3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 abstract class CRM_Import_Parser
{
21 const MAX_WARNINGS
= 25, DEFAULT_TIMEOUT
= 30;
26 const VALID
= 1, WARNING
= 2, ERROR
= 4, CONFLICT
= 8, STOP
= 16, DUPLICATE
= 32, MULTIPLE_DUPE
= 64, NO_MATCH
= 128, UNPARSED_ADDRESS_WARNING
= 256;
31 const MODE_MAPFIELD
= 1, MODE_PREVIEW
= 2, MODE_SUMMARY
= 4, MODE_IMPORT
= 8;
34 * Codes for duplicate record handling
36 const DUPLICATE_SKIP
= 1, DUPLICATE_REPLACE
= 2, DUPLICATE_UPDATE
= 4, DUPLICATE_FILL
= 8, DUPLICATE_NOCHECK
= 16;
41 const CONTACT_INDIVIDUAL
= 1, CONTACT_HOUSEHOLD
= 2, CONTACT_ORGANIZATION
= 4;
45 * Total number of non empty lines
48 protected $_totalCount;
51 * Running total number of valid lines
54 protected $_validCount;
57 * Running total number of invalid rows
60 protected $_invalidRowCount;
63 * Maximum number of non-empty/comment lines to process
67 protected $_maxLinesToProcess;
70 * Array of error lines, bounded by MAX_ERROR
76 * Total number of conflict lines
79 protected $_conflictCount;
82 * Array of conflict lines
85 protected $_conflicts;
88 * Total number of duplicate (from database) lines
91 protected $_duplicateCount;
94 * Array of duplicate lines
97 protected $_duplicates;
100 * Running total number of warnings
103 protected $_warningCount;
106 * Maximum number of warnings to store
109 protected $_maxWarningCount = self
::MAX_WARNINGS
;
112 * Array of warning lines, bounded by MAX_WARNING
115 protected $_warnings;
118 * Array of all the fields that could potentially be part
119 * of this import process
125 * Metadata for all available fields, keyed by unique name.
127 * This is intended to supercede $_fields which uses a special sauce format which
128 * importableFieldsMetadata uses the standard getfields type format.
132 protected $importableFieldsMetadata = [];
135 * Get metadata for all importable fields in std getfields style format.
139 public function getImportableFieldsMetadata(): array {
140 return $this->importableFieldsMetadata
;
144 * Set metadata for all importable fields in std getfields style format.
146 * @param array $importableFieldsMetadata
148 public function setImportableFieldsMetadata(array $importableFieldsMetadata): void
{
149 $this->importableFieldsMetadata
= $importableFieldsMetadata;
153 * Array of the fields that are actually part of the import process
154 * the position in the array also dictates their position in the import
158 protected $_activeFields;
161 * Cache the count of active fields
165 protected $_activeFieldCount;
168 * Cache of preview rows
175 * Filename of error data
179 protected $_errorFileName;
182 * Filename of conflict data
186 protected $_conflictFileName;
189 * Filename of duplicate data
193 protected $_duplicateFileName;
200 public $_contactType;
206 public $_contactSubType;
211 public function __construct() {
212 $this->_maxLinesToProcess
= 0;
216 * Abstract function definitions.
218 abstract protected function init();
223 abstract protected function fini();
228 * @param array $values
232 abstract protected function mapField(&$values);
237 * @param array $values
241 abstract protected function preview(&$values);
248 abstract protected function summary(&$values);
251 * @param $onDuplicate
256 abstract protected function import($onDuplicate, &$values);
259 * Set and validate field values.
261 * @param array $elements
263 * @param $erroneousField
268 public function setActiveFieldValues($elements, &$erroneousField = NULL) {
269 $maxCount = count($elements) < $this->_activeFieldCount ?
count($elements) : $this->_activeFieldCount
;
270 for ($i = 0; $i < $maxCount; $i++
) {
271 $this->_activeFields
[$i]->setValue($elements[$i]);
274 // reset all the values that we did not have an equivalent import element
275 for (; $i < $this->_activeFieldCount
; $i++
) {
276 $this->_activeFields
[$i]->resetValue();
279 // now validate the fields and return false if error
280 $valid = self
::VALID
;
281 for ($i = 0; $i < $this->_activeFieldCount
; $i++
) {
282 if (!$this->_activeFields
[$i]->validate()) {
283 // no need to do any more validation
284 $erroneousField = $i;
285 $valid = self
::ERROR
;
293 * Format the field values for input to the api.
296 * (reference) associative array of name/value pairs
298 public function &getActiveFieldParams() {
300 for ($i = 0; $i < $this->_activeFieldCount
; $i++
) {
301 if (isset($this->_activeFields
[$i]->_value
)
302 && !isset($params[$this->_activeFields
[$i]->_name
])
303 && !isset($this->_activeFields
[$i]->_related
)
306 $params[$this->_activeFields
[$i]->_name
] = $this->_activeFields
[$i]->_value
;
313 * Add progress bar to the import process. Calculates time remaining, status etc.
316 * status id of the import process saved in $config->uploadDir.
317 * @param bool $startImport
318 * True when progress bar is to be initiated.
319 * @param $startTimestamp
320 * Initial timestamp when the import was started.
321 * @param $prevTimestamp
322 * Previous timestamp when this function was last called.
323 * @param $totalRowCount
324 * Total number of rows in the import file.
326 * @return NULL|$currTimestamp
328 public function progressImport($statusID, $startImport = TRUE, $startTimestamp = NULL, $prevTimestamp = NULL, $totalRowCount = NULL) {
329 $statusFile = CRM_Core_Config
::singleton()->uploadDir
. "status_{$statusID}.txt";
332 $status = "<div class='description'> " . ts('No processing status reported yet.') . "</div>";
333 //do not force the browser to display the save dialog, CRM-7640
334 $contents = json_encode([0, $status]);
335 file_put_contents($statusFile, $contents);
338 $rowCount = $this->_rowCount ??
$this->_lineCount
;
339 $currTimestamp = time();
340 $time = ($currTimestamp - $prevTimestamp);
341 $recordsLeft = $totalRowCount - $rowCount;
342 if ($recordsLeft < 0) {
345 $estimatedTime = ($recordsLeft / 50) * $time;
346 $estMinutes = floor($estimatedTime / 60);
348 if ($estMinutes > 1) {
349 $timeFormatted = $estMinutes . ' ' . ts('minutes') . ' ';
350 $estimatedTime = $estimatedTime - ($estMinutes * 60);
352 $timeFormatted .= round($estimatedTime) . ' ' . ts('seconds');
353 $processedPercent = (int ) (($rowCount * 100) / $totalRowCount);
354 $statusMsg = ts('%1 of %2 records - %3 remaining',
355 [1 => $rowCount, 2 => $totalRowCount, 3 => $timeFormatted]
357 $status = "<div class=\"description\"> <strong>{$statusMsg}</strong></div>";
358 $contents = json_encode([$processedPercent, $status]);
360 file_put_contents($statusFile, $contents);
361 return $currTimestamp;
368 public function getSelectValues(): array {
370 foreach ($this->_fields
as $name => $field) {
371 $values[$name] = $field->_title
;
379 public function getSelectTypes() {
381 foreach ($this->_fields
as $name => $field) {
382 if (isset($field->_hasLocationType
)) {
383 $values[$name] = $field->_hasLocationType
;
392 public function getHeaderPatterns() {
394 foreach ($this->_fields
as $name => $field) {
395 if (isset($field->_headerPattern
)) {
396 $values[$name] = $field->_headerPattern
;
405 public function getDataPatterns() {
407 foreach ($this->_fields
as $name => $field) {
408 $values[$name] = $field->_dataPattern
;
414 * Remove single-quote enclosures from a value array (row).
416 * @param array $values
417 * @param string $enclosure
421 public static function encloseScrub(&$values, $enclosure = "'") {
422 if (empty($values)) {
426 foreach ($values as $k => $v) {
427 $values[$k] = preg_replace("/^$enclosure(.*)$enclosure$/", '$1', $v);
438 public function setMaxLinesToProcess($max) {
439 $this->_maxLinesToProcess
= $max;
443 * Determines the file extension based on error code.
445 * @var $type error code constant
448 public static function errorFileName($type) {
454 $config = CRM_Core_Config
::singleton();
455 $fileName = $config->uploadDir
. "sqlImport";
458 $fileName .= '.errors';
462 $fileName .= '.conflicts';
465 case self
::DUPLICATE
:
466 $fileName .= '.duplicates';
470 $fileName .= '.mismatch';
473 case self
::UNPARSED_ADDRESS_WARNING
:
474 $fileName .= '.unparsedAddress';
482 * Determines the file name based on error code.
484 * @var $type error code constant
487 public static function saveFileName($type) {
494 $fileName = 'Import_Errors.csv';
498 $fileName = 'Import_Conflicts.csv';
501 case self
::DUPLICATE
:
502 $fileName = 'Import_Duplicates.csv';
506 $fileName = 'Import_Mismatch.csv';
509 case self
::UNPARSED_ADDRESS_WARNING
:
510 $fileName = 'Import_Unparsed_Address.csv';
518 * Check if contact is a duplicate .
520 * @param array $formatValues
524 protected function checkContactDuplicate(&$formatValues) {
525 //retrieve contact id using contact dedupe rule
526 $formatValues['contact_type'] = $formatValues['contact_type'] ??
$this->_contactType
;
527 $formatValues['version'] = 3;
528 require_once 'CRM/Utils/DeprecatedUtils.php';
529 $params = $formatValues;
530 static $cIndieFields = NULL;
531 static $defaultLocationId = NULL;
533 $contactType = $params['contact_type'];
534 if ($cIndieFields == NULL) {
535 $cTempIndieFields = CRM_Contact_BAO_Contact
::importableFields($contactType);
536 $cIndieFields = $cTempIndieFields;
538 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
540 // set the value to default location id else set to 1
541 if (!$defaultLocationId = (int) $defaultLocation->id
) {
542 $defaultLocationId = 1;
546 $locationFields = CRM_Contact_BAO_Query
::$_locationSpecificFields;
548 $contactFormatted = [];
549 foreach ($params as $key => $field) {
550 if ($field == NULL ||
$field === '') {
553 // CRM-17040, Considering only primary contact when importing contributions. So contribution inserts into primary contact
554 // instead of soft credit contact.
555 if (is_array($field) && $key != "soft_credit") {
556 foreach ($field as $value) {
558 if (is_array($value)) {
559 foreach ($value as $name => $testForEmpty) {
560 if ($name !== 'phone_type' &&
561 ($testForEmpty === '' ||
$testForEmpty == NULL)
572 _civicrm_api3_deprecated_add_formatted_param($value, $contactFormatted);
578 $value = [$key => $field];
580 // check if location related field, then we need to add primary location type
581 if (in_array($key, $locationFields)) {
582 $value['location_type_id'] = $defaultLocationId;
584 elseif (array_key_exists($key, $cIndieFields)) {
585 $value['contact_type'] = $contactType;
588 _civicrm_api3_deprecated_add_formatted_param($value, $contactFormatted);
591 $contactFormatted['contact_type'] = $contactType;
593 return _civicrm_api3_deprecated_duplicate_formatted_contact($contactFormatted);
597 * Parse a field which could be represented by a label or name value rather than the DB value.
599 * We will try to match name first or (per https://lab.civicrm.org/dev/core/issues/1285 if we have an id.
601 * but if not available then see if we have a label that can be converted to a name.
603 * @param string|int|null $submittedValue
604 * @param array $fieldSpec
605 * Metadata for the field
609 protected function parsePseudoConstantField($submittedValue, $fieldSpec) {
610 // dev/core#1289 Somehow we have wound up here but the BAO has not been specified in the fieldspec so we need to check this but future us problem, for now lets just return the submittedValue
611 if (!isset($fieldSpec['bao'])) {
612 return $submittedValue;
614 /* @var \CRM_Core_DAO $bao */
615 $bao = $fieldSpec['bao'];
616 // For historical reasons use validate as context - ie disabled name matches ARE permitted.
617 $nameOptions = $bao::buildOptions($fieldSpec['name'], 'validate');
618 if (isset($nameOptions[$submittedValue])) {
619 return $submittedValue;
621 if (in_array($submittedValue, $nameOptions)) {
622 return array_search($submittedValue, $nameOptions, TRUE);
625 $labelOptions = array_flip($bao::buildOptions($fieldSpec['name'], 'match'));
626 if (isset($labelOptions[$submittedValue])) {
627 return array_search($labelOptions[$submittedValue], $nameOptions, TRUE);
633 * This is code extracted from 4 places where this exact snippet was being duplicated.
635 * FIXME: Extracting this was a first step, but there's also
636 * 1. Inconsistency in the way other select options are handled.
637 * Contribution adds handling for Select/Radio/Autocomplete
638 * Participant/Activity only handles Select/Radio and misses Autocomplete
639 * Membership is missing all of it
640 * 2. Inconsistency with the way this works vs. how it's implemented in Contact import.
642 * @param $customFieldID
647 public static function unserializeCustomValue($customFieldID, $value, $fieldType) {
648 $mulValues = explode(',', $value);
649 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldID, TRUE);
651 foreach ($mulValues as $v1) {
652 foreach ($customOption as $customValueID => $customLabel) {
653 $customValue = $customLabel['value'];
654 if ((strtolower(trim($customLabel['label'])) == strtolower(trim($v1))) ||
655 (strtolower(trim($customValue)) == strtolower(trim($v1)))
657 if ($fieldType == 'CheckBox') {
658 $values[$customValue] = 1;
661 $values[] = $customValue;
670 * Get the ids of any contacts that match according to the rule.
672 * @param array $formatted
676 protected function getIdsOfMatchingContacts(array $formatted):array {
677 // the call to the deprecated function seems to add no value other that to do an additional
678 // check for the contact_id & type.
679 $error = _civicrm_api3_deprecated_duplicate_formatted_contact($formatted);
680 if (!CRM_Core_Error
::isAPIError($error, CRM_Core_ERROR
::DUPLICATE_CONTACT
)) {
683 if (is_array($error['error_message']['params'][0])) {
684 return $error['error_message']['params'][0];
687 return explode(',', $error['error_message']['params'][0]);