3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
33 abstract class CRM_Contact_Import_Parser
extends CRM_Import_Parser
{
35 protected $_tableName;
38 * Total number of lines in file
45 * Running total number of un-matched Contacts.
48 protected $_unMatchCount;
51 * Array of unmatched lines
57 * Total number of contacts with unparsed addresses
60 protected $_unparsedAddressCount;
63 * Filename of mismatch data
67 protected $_misMatchFilemName;
69 protected $_primaryKeyName;
70 protected $_statusFieldName;
72 protected $fieldMetadata = [];
81 * Dedupe rule group id to use if set
85 public $_dedupeRuleGroupID = NULL;
90 * @param string $tableName
91 * @param array $mapper
93 * @param int $contactType
94 * @param string $primaryKeyName
95 * @param string $statusFieldName
96 * @param int $onDuplicate
97 * @param int $statusID
98 * @param int $totalRowCount
99 * @param bool $doGeocodeAddress
100 * @param int $timeout
101 * @param string $contactSubType
102 * @param int $dedupeRuleGroupID
109 $mode = self
::MODE_PREVIEW
,
110 $contactType = self
::CONTACT_INDIVIDUAL
,
111 $primaryKeyName = '_id',
112 $statusFieldName = '_status',
113 $onDuplicate = self
::DUPLICATE_SKIP
,
115 $totalRowCount = NULL,
116 $doGeocodeAddress = FALSE,
117 $timeout = CRM_Contact_Import_Parser
::DEFAULT_TIMEOUT
,
118 $contactSubType = NULL,
119 $dedupeRuleGroupID = NULL
122 // TODO: Make the timeout actually work
123 $this->_onDuplicate
= $onDuplicate;
124 $this->_dedupeRuleGroupID
= $dedupeRuleGroupID;
126 switch ($contactType) {
127 case CRM_Import_Parser
::CONTACT_INDIVIDUAL
:
128 $this->_contactType
= 'Individual';
131 case CRM_Import_Parser
::CONTACT_HOUSEHOLD
:
132 $this->_contactType
= 'Household';
135 case CRM_Import_Parser
::CONTACT_ORGANIZATION
:
136 $this->_contactType
= 'Organization';
139 $this->_contactSubType
= $contactSubType;
143 $this->_rowCount
= $this->_warningCount
= 0;
144 $this->_invalidRowCount
= $this->_validCount
= 0;
145 $this->_totalCount
= $this->_conflictCount
= 0;
148 $this->_warnings
= [];
149 $this->_conflicts
= [];
150 $this->_unparsedAddresses
= [];
152 $this->_tableName
= $tableName;
153 $this->_primaryKeyName
= $primaryKeyName;
154 $this->_statusFieldName
= $statusFieldName;
156 if ($mode == self
::MODE_MAPFIELD
) {
160 $this->_activeFieldCount
= count($this->_activeFields
);
163 if ($mode == self
::MODE_IMPORT
) {
164 //get the key of email field
165 foreach ($mapper as $key => $value) {
166 if (strtolower($value) == 'email') {
174 $this->progressImport($statusID);
175 $startTimestamp = $currTimestamp = $prevTimestamp = time();
177 // get the contents of the temp. import table
178 $query = "SELECT * FROM $tableName";
179 if ($mode == self
::MODE_IMPORT
) {
180 $query .= " WHERE $statusFieldName = 'NEW'";
182 $dao = new CRM_Core_DAO();
183 $db = $dao->getDatabaseConnection();
184 $result = $db->query($query);
186 while ($values = $result->fetchRow(DB_FETCHMODE_ORDERED
)) {
189 /* trim whitespace around the values */
190 foreach ($values as $k => $v) {
191 $values[$k] = trim($v, " \t\r\n");
193 if (CRM_Utils_System
::isNull($values)) {
197 $this->_totalCount++
;
199 if ($mode == self
::MODE_MAPFIELD
) {
200 $returnCode = $this->mapField($values);
202 elseif ($mode == self
::MODE_PREVIEW
) {
203 $returnCode = $this->preview($values);
205 elseif ($mode == self
::MODE_SUMMARY
) {
206 $returnCode = $this->summary($values);
208 elseif ($mode == self
::MODE_IMPORT
) {
209 //print "Running parser in import mode<br/>\n";
210 $returnCode = $this->import($onDuplicate, $values, $doGeocodeAddress);
211 if ($statusID && (($this->_rowCount %
50) == 0)) {
212 $prevTimestamp = $this->progressImport($statusID, FALSE, $startTimestamp, $prevTimestamp, $totalRowCount);
216 $returnCode = self
::ERROR
;
219 // note that a line could be valid but still produce a warning
220 if ($returnCode & self
::VALID
) {
221 $this->_validCount++
;
222 if ($mode == self
::MODE_MAPFIELD
) {
223 $this->_rows
[] = $values;
224 $this->_activeFieldCount
= max($this->_activeFieldCount
, count($values));
228 if ($returnCode & self
::WARNING
) {
229 $this->_warningCount++
;
230 if ($this->_warningCount
< $this->_maxWarningCount
) {
231 $this->_warningCount
[] = $line;
235 if ($returnCode & self
::ERROR
) {
236 $this->_invalidRowCount++
;
237 array_unshift($values, $this->_rowCount
);
238 $this->_errors
[] = $values;
241 if ($returnCode & self
::CONFLICT
) {
242 $this->_conflictCount++
;
243 array_unshift($values, $this->_rowCount
);
244 $this->_conflicts
[] = $values;
247 if ($returnCode & self
::NO_MATCH
) {
248 $this->_unMatchCount++
;
249 array_unshift($values, $this->_rowCount
);
250 $this->_unMatch
[] = $values;
253 if ($returnCode & self
::DUPLICATE
) {
254 if ($returnCode & self
::MULTIPLE_DUPE
) {
255 /* TODO: multi-dupes should be counted apart from singles
256 * on non-skip action */
258 $this->_duplicateCount++
;
259 array_unshift($values, $this->_rowCount
);
260 $this->_duplicates
[] = $values;
261 if ($onDuplicate != self
::DUPLICATE_SKIP
) {
262 $this->_validCount++
;
266 if ($returnCode & self
::UNPARSED_ADDRESS_WARNING
) {
267 $this->_unparsedAddressCount++
;
268 array_unshift($values, $this->_rowCount
);
269 $this->_unparsedAddresses
[] = $values;
271 // we give the derived class a way of aborting the process
272 // note that the return code could be multiple code or'ed together
273 if ($returnCode & self
::STOP
) {
277 // if we are done processing the maxNumber of lines, break
278 if ($this->_maxLinesToProcess
> 0 && $this->_validCount
>= $this->_maxLinesToProcess
) {
282 // see if we've hit our timeout yet
283 /* if ( $the_thing_with_the_stuff ) {
288 if ($mode == self
::MODE_PREVIEW ||
$mode == self
::MODE_IMPORT
) {
289 $customHeaders = $mapper;
291 $customfields = CRM_Core_BAO_CustomField
::getFields($this->_contactType
);
292 foreach ($customHeaders as $key => $value) {
293 if ($id = CRM_Core_BAO_CustomField
::getKeyID($value)) {
294 $customHeaders[$key] = $customfields[$id][0];
298 if ($this->_invalidRowCount
) {
299 // removed view url for invlaid contacts
300 $headers = array_merge([
304 $this->_errorFileName
= self
::errorFileName(self
::ERROR
);
305 self
::exportCSV($this->_errorFileName
, $headers, $this->_errors
);
307 if ($this->_conflictCount
) {
308 $headers = array_merge([
312 $this->_conflictFileName
= self
::errorFileName(self
::CONFLICT
);
313 self
::exportCSV($this->_conflictFileName
, $headers, $this->_conflicts
);
315 if ($this->_duplicateCount
) {
316 $headers = array_merge([
318 ts('View Contact URL'),
321 $this->_duplicateFileName
= self
::errorFileName(self
::DUPLICATE
);
322 self
::exportCSV($this->_duplicateFileName
, $headers, $this->_duplicates
);
324 if ($this->_unMatchCount
) {
325 $headers = array_merge([
330 $this->_misMatchFilemName
= self
::errorFileName(self
::NO_MATCH
);
331 self
::exportCSV($this->_misMatchFilemName
, $headers, $this->_unMatch
);
333 if ($this->_unparsedAddressCount
) {
334 $headers = array_merge([
336 ts('Contact Edit URL'),
338 $this->_errorFileName
= self
::errorFileName(self
::UNPARSED_ADDRESS_WARNING
);
339 self
::exportCSV($this->_errorFileName
, $headers, $this->_unparsedAddresses
);
342 //echo "$this->_totalCount,$this->_invalidRowCount,$this->_conflictCount,$this->_duplicateCount";
343 return $this->fini();
347 * Given a list of the importable field keys that the user has selected.
348 * set the active fields array to this list
350 * @param array $fieldKeys
351 * Mapped array of values.
353 public function setActiveFields($fieldKeys) {
354 $this->_activeFieldCount
= count($fieldKeys);
355 foreach ($fieldKeys as $key) {
356 if (empty($this->_fields
[$key])) {
357 $this->_activeFields
[] = new CRM_Contact_Import_Field('', ts('- do not import -'));
360 $this->_activeFields
[] = clone($this->_fields
[$key]);
368 public function setActiveFieldLocationTypes($elements) {
369 for ($i = 0; $i < count($elements); $i++
) {
370 $this->_activeFields
[$i]->_hasLocationType
= $elements[$i];
381 public function setActiveFieldPhoneTypes($elements) {
382 for ($i = 0; $i < count($elements); $i++
) {
383 $this->_activeFields
[$i]->_phoneType
= $elements[$i];
390 public function setActiveFieldWebsiteTypes($elements) {
391 for ($i = 0; $i < count($elements); $i++
) {
392 $this->_activeFields
[$i]->_websiteType
= $elements[$i];
397 * Set IM Service Provider type fields.
399 * @param array $elements
400 * IM service provider type ids.
402 public function setActiveFieldImProviders($elements) {
403 for ($i = 0; $i < count($elements); $i++
) {
404 $this->_activeFields
[$i]->_imProvider
= $elements[$i];
411 public function setActiveFieldRelated($elements) {
412 for ($i = 0; $i < count($elements); $i++
) {
413 $this->_activeFields
[$i]->_related
= $elements[$i];
420 public function setActiveFieldRelatedContactType($elements) {
421 for ($i = 0; $i < count($elements); $i++
) {
422 $this->_activeFields
[$i]->_relatedContactType
= $elements[$i];
429 public function setActiveFieldRelatedContactDetails($elements) {
430 for ($i = 0; $i < count($elements); $i++
) {
431 $this->_activeFields
[$i]->_relatedContactDetails
= $elements[$i];
438 public function setActiveFieldRelatedContactLocType($elements) {
439 for ($i = 0; $i < count($elements); $i++
) {
440 $this->_activeFields
[$i]->_relatedContactLocType
= $elements[$i];
445 * Set active field for related contact's phone type.
447 * @param array $elements
449 public function setActiveFieldRelatedContactPhoneType($elements) {
450 for ($i = 0; $i < count($elements); $i++
) {
451 $this->_activeFields
[$i]->_relatedContactPhoneType
= $elements[$i];
458 public function setActiveFieldRelatedContactWebsiteType($elements) {
459 for ($i = 0; $i < count($elements); $i++
) {
460 $this->_activeFields
[$i]->_relatedContactWebsiteType
= $elements[$i];
465 * Set IM Service Provider type fields for related contacts.
467 * @param array $elements
468 * IM service provider type ids of related contact.
470 public function setActiveFieldRelatedContactImProvider($elements) {
471 for ($i = 0; $i < count($elements); $i++
) {
472 $this->_activeFields
[$i]->_relatedContactImProvider
= $elements[$i];
477 * Format the field values for input to the api.
480 * (reference ) associative array of name/value pairs
482 public function &getActiveFieldParams() {
485 for ($i = 0; $i < $this->_activeFieldCount
; $i++
) {
486 if ($this->_activeFields
[$i]->_name
== 'do_not_import') {
490 if (isset($this->_activeFields
[$i]->_value
)) {
491 if (isset($this->_activeFields
[$i]->_hasLocationType
)) {
492 if (!isset($params[$this->_activeFields
[$i]->_name
])) {
493 $params[$this->_activeFields
[$i]->_name
] = [];
497 $this->_activeFields
[$i]->_name
=> $this->_activeFields
[$i]->_value
,
498 'location_type_id' => $this->_activeFields
[$i]->_hasLocationType
,
501 if (isset($this->_activeFields
[$i]->_phoneType
)) {
502 $value['phone_type_id'] = $this->_activeFields
[$i]->_phoneType
;
505 // get IM service Provider type id
506 if (isset($this->_activeFields
[$i]->_imProvider
)) {
507 $value['provider_id'] = $this->_activeFields
[$i]->_imProvider
;
510 $params[$this->_activeFields
[$i]->_name
][] = $value;
512 elseif (isset($this->_activeFields
[$i]->_websiteType
)) {
514 $this->_activeFields
[$i]->_name
=> $this->_activeFields
[$i]->_value
,
515 'website_type_id' => $this->_activeFields
[$i]->_websiteType
,
518 $params[$this->_activeFields
[$i]->_name
][] = $value;
521 if (!isset($params[$this->_activeFields
[$i]->_name
])) {
522 if (!isset($this->_activeFields
[$i]->_related
)) {
523 $params[$this->_activeFields
[$i]->_name
] = $this->_activeFields
[$i]->_value
;
527 //minor fix for CRM-4062
528 if (isset($this->_activeFields
[$i]->_related
)) {
529 if (!isset($params[$this->_activeFields
[$i]->_related
])) {
530 $params[$this->_activeFields
[$i]->_related
] = [];
533 if (!isset($params[$this->_activeFields
[$i]->_related
]['contact_type']) && !empty($this->_activeFields
[$i]->_relatedContactType
)) {
534 $params[$this->_activeFields
[$i]->_related
]['contact_type'] = $this->_activeFields
[$i]->_relatedContactType
;
537 if (isset($this->_activeFields
[$i]->_relatedContactLocType
) && !empty($this->_activeFields
[$i]->_value
)) {
538 if (!empty($params[$this->_activeFields
[$i]->_related
][$this->_activeFields
[$i]->_relatedContactDetails
]) &&
539 !is_array($params[$this->_activeFields
[$i]->_related
][$this->_activeFields
[$i]->_relatedContactDetails
])
541 $params[$this->_activeFields
[$i]->_related
][$this->_activeFields
[$i]->_relatedContactDetails
] = [];
544 $this->_activeFields
[$i]->_relatedContactDetails
=> $this->_activeFields
[$i]->_value
,
545 'location_type_id' => $this->_activeFields
[$i]->_relatedContactLocType
,
548 if (isset($this->_activeFields
[$i]->_relatedContactPhoneType
)) {
549 $value['phone_type_id'] = $this->_activeFields
[$i]->_relatedContactPhoneType
;
552 // get IM service Provider type id for related contact
553 if (isset($this->_activeFields
[$i]->_relatedContactImProvider
)) {
554 $value['provider_id'] = $this->_activeFields
[$i]->_relatedContactImProvider
;
557 $params[$this->_activeFields
[$i]->_related
][$this->_activeFields
[$i]->_relatedContactDetails
][] = $value;
559 elseif (isset($this->_activeFields
[$i]->_relatedContactWebsiteType
)) {
560 $params[$this->_activeFields
[$i]->_related
][$this->_activeFields
[$i]->_relatedContactDetails
][] = [
561 'url' => $this->_activeFields
[$i]->_value
,
562 'website_type_id' => $this->_activeFields
[$i]->_relatedContactWebsiteType
,
566 $params[$this->_activeFields
[$i]->_related
][$this->_activeFields
[$i]->_relatedContactDetails
] = $this->_activeFields
[$i]->_value
;
578 public function getColumnPatterns() {
580 foreach ($this->_fields
as $name => $field) {
581 $values[$name] = $field->_columnPattern
;
587 * @param string $name
590 * @param string $headerPattern
591 * @param string $dataPattern
592 * @param bool $hasLocationType
594 public function addField(
595 $name, $title, $type = CRM_Utils_Type
::T_INT
,
596 $headerPattern = '//', $dataPattern = '//',
597 $hasLocationType = FALSE
599 $this->_fields
[$name] = new CRM_Contact_Import_Field($name, $title, $type, $headerPattern, $dataPattern, $hasLocationType);
601 $this->_fields
['doNotImport'] = new CRM_Contact_Import_Field($name, $title, $type, $headerPattern, $dataPattern, $hasLocationType);
606 * Store parser values.
608 * @param CRM_Core_Session $store
612 public function set($store, $mode = self
::MODE_SUMMARY
) {
613 $store->set('rowCount', $this->_rowCount
);
614 $store->set('fields', $this->getSelectValues());
615 $store->set('fieldTypes', $this->getSelectTypes());
617 $store->set('columnPatterns', $this->getColumnPatterns());
618 $store->set('dataPatterns', $this->getDataPatterns());
619 $store->set('columnCount', $this->_activeFieldCount
);
621 $store->set('totalRowCount', $this->_totalCount
);
622 $store->set('validRowCount', $this->_validCount
);
623 $store->set('invalidRowCount', $this->_invalidRowCount
);
624 $store->set('conflictRowCount', $this->_conflictCount
);
625 $store->set('unMatchCount', $this->_unMatchCount
);
627 switch ($this->_contactType
) {
629 $store->set('contactType', CRM_Import_Parser
::CONTACT_INDIVIDUAL
);
633 $store->set('contactType', CRM_Import_Parser
::CONTACT_HOUSEHOLD
);
637 $store->set('contactType', CRM_Import_Parser
::CONTACT_ORGANIZATION
);
640 if ($this->_invalidRowCount
) {
641 $store->set('errorsFileName', $this->_errorFileName
);
643 if ($this->_conflictCount
) {
644 $store->set('conflictsFileName', $this->_conflictFileName
);
646 if (isset($this->_rows
) && !empty($this->_rows
)) {
647 $store->set('dataValues', $this->_rows
);
650 if ($this->_unMatchCount
) {
651 $store->set('mismatchFileName', $this->_misMatchFilemName
);
654 if ($mode == self
::MODE_IMPORT
) {
655 $store->set('duplicateRowCount', $this->_duplicateCount
);
656 $store->set('unparsedAddressCount', $this->_unparsedAddressCount
);
657 if ($this->_duplicateCount
) {
658 $store->set('duplicatesFileName', $this->_duplicateFileName
);
660 if ($this->_unparsedAddressCount
) {
661 $store->set('errorsFileName', $this->_errorFileName
);
664 //echo "$this->_totalCount,$this->_invalidRowCount,$this->_conflictCount,$this->_duplicateCount";
668 * Export data to a CSV file.
670 * @param string $fileName
671 * @param array $header
674 public static function exportCSV($fileName, $header, $data) {
676 if (file_exists($fileName) && !is_writable($fileName)) {
677 CRM_Core_Error
::movedSiteError($fileName);
679 //hack to remove '_status', '_statusMsg' and '_id' from error file
681 $dbRecordStatus = ['IMPORTED', 'ERROR', 'DUPLICATE', 'INVALID', 'NEW'];
682 foreach ($data as $rowCount => $rowValues) {
684 foreach ($rowValues as $key => $val) {
685 if (in_array($val, $dbRecordStatus) && $count == (count($rowValues) - 3)) {
688 $errorValues[$rowCount][$key] = $val;
692 $data = $errorValues;
695 $fd = fopen($fileName, 'w');
697 foreach ($header as $key => $value) {
698 $header[$key] = "\"$value\"";
700 $config = CRM_Core_Config
::singleton();
701 $output[] = implode($config->fieldSeparator
, $header);
703 foreach ($data as $datum) {
704 foreach ($datum as $key => $value) {
705 $datum[$key] = "\"$value\"";
707 $output[] = implode($config->fieldSeparator
, $datum);
709 fwrite($fd, implode("\n", $output));
714 * Update the record with PK $id in the import database table.
717 * @param array $params
719 public function updateImportRecord($id, &$params) {
720 $statusFieldName = $this->_statusFieldName
;
721 $primaryKeyName = $this->_primaryKeyName
;
723 if ($statusFieldName && $primaryKeyName) {
724 $dao = new CRM_Core_DAO();
725 $db = $dao->getDatabaseConnection();
727 $query = "UPDATE $this->_tableName
728 SET $statusFieldName = ?,
729 ${statusFieldName}Msg = ?
730 WHERE $primaryKeyName = ?";
732 $params[$statusFieldName],
733 CRM_Utils_Array
::value("${statusFieldName}Msg", $params),
737 //print "Running query: $query<br/>With arguments: ".$params[$statusFieldName].", ".$params["${statusFieldName}Msg"].", $id<br/>";
739 $db->query($query, $args);
744 * Format common params data to proper format to store.
746 * @param array $params
747 * Contain record values.
748 * @param array $formatted
749 * Array of formatted data.
750 * @param array $contactFields
751 * Contact DAO fields.
753 public function formatCommonData($params, &$formatted, &$contactFields) {
755 CRM_Utils_Array
::value('contact_type', $formatted),
759 //add custom fields for contact sub type
760 if (!empty($this->_contactSubType
)) {
761 $csType = $this->_contactSubType
;
764 if ($relCsType = CRM_Utils_Array
::value('contact_sub_type', $formatted)) {
765 $csType = $relCsType;
768 $customFields = CRM_Core_BAO_CustomField
::getFields($formatted['contact_type'], FALSE, FALSE, $csType);
770 $addressCustomFields = CRM_Core_BAO_CustomField
::getFields('Address');
771 $customFields = $customFields +
$addressCustomFields;
773 //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
775 'email_greeting_custom' => 'email_greeting',
776 'postal_greeting_custom' => 'postal_greeting',
777 'addressee_custom' => 'addressee',
779 foreach ($elements as $k => $v) {
780 if (array_key_exists($k, $params) && !(array_key_exists($v, $params))) {
781 $label = key(CRM_Core_OptionGroup
::values($v, TRUE, NULL, NULL, 'AND v.name = "Customized"'));
782 $params[$v] = $label;
787 $session = CRM_Core_Session
::singleton();
788 $dateType = $session->get("dateTypes");
789 foreach ($params as $key => $val) {
790 $customFieldID = CRM_Core_BAO_CustomField
::getKeyID($key);
791 if ($customFieldID &&
792 !array_key_exists($customFieldID, $addressCustomFields)
794 //we should not update Date to null, CRM-4062
795 if ($val && ($customFields[$customFieldID]['data_type'] == 'Date')) {
797 CRM_Contact_Import_Parser_Contact
::formatCustomDate($params, $formatted, $dateType, $key);
799 elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
800 if (empty($val) && !is_numeric($val) && $this->_onDuplicate
== CRM_Import_Parser
::DUPLICATE_FILL
) {
801 //retain earlier value when Import mode is `Fill`
802 unset($params[$key]);
805 $params[$key] = CRM_Utils_String
::strtoboolstr($val);
810 if ($key == 'birth_date' && $val) {
811 CRM_Utils_Date
::convertToDefaultDate($params, $dateType, $key);
813 elseif ($key == 'deceased_date' && $val) {
814 CRM_Utils_Date
::convertToDefaultDate($params, $dateType, $key);
815 $params['is_deceased'] = 1;
817 elseif ($key == 'is_deceased' && $val) {
818 $params[$key] = CRM_Utils_String
::strtoboolstr($val);
820 elseif ($key == 'gender') {
822 $params[$key] = $this->checkGender($val);
826 //now format custom data.
827 foreach ($params as $key => $field) {
828 if (is_array($field)) {
829 $isAddressCustomField = FALSE;
830 foreach ($field as $value) {
832 if (is_array($value)) {
833 foreach ($value as $name => $testForEmpty) {
834 if ($addressCustomFieldID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
835 $isAddressCustomField = TRUE;
838 // check if $value does not contain IM provider or phoneType
839 if (($name !== 'phone_type_id' ||
$name !== 'provider_id') && ($testForEmpty === '' ||
$testForEmpty == NULL)) {
850 $this->formatContactParameters($value, $formatted);
853 if (!$isAddressCustomField) {
862 if (($key !== 'preferred_communication_method') && (array_key_exists($key, $contactFields))) {
863 // due to merging of individual table and
864 // contact table, we need to avoid
865 // preferred_communication_method forcefully
866 $formatValues['contact_type'] = $formatted['contact_type'];
869 if ($key == 'id' && isset($field)) {
870 $formatted[$key] = $field;
872 $this->formatContactParameters($formatValues, $formatted);
874 //Handling Custom Data
875 // note: Address custom fields will be handled separately inside formatContactParameters
876 if (($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($key)) &&
877 array_key_exists($customFieldID, $customFields) &&
878 !array_key_exists($customFieldID, $addressCustomFields)
881 $extends = CRM_Utils_Array
::value('extends', $customFields[$customFieldID]);
882 $htmlType = CRM_Utils_Array
::value('html_type', $customFields[$customFieldID]);
886 case 'Autocomplete-Select':
887 if ($customFields[$customFieldID]['data_type'] == 'String' ||
$customFields[$customFieldID]['data_type'] == 'Int') {
888 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldID, TRUE);
889 foreach ($customOption as $customValue) {
890 $val = CRM_Utils_Array
::value('value', $customValue);
891 $label = CRM_Utils_Array
::value('label', $customValue);
892 $label = strtolower($label);
893 $value = strtolower(trim($formatted[$key]));
894 if (($value == $label) ||
($value == strtolower($val))) {
895 $params[$key] = $formatted[$key] = $val;
904 if (!empty($formatted[$key]) && !empty($params[$key])) {
905 $mulValues = explode(',', $formatted[$key]);
906 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldID, TRUE);
907 $formatted[$key] = [];
909 foreach ($mulValues as $v1) {
910 foreach ($customOption as $v2) {
911 if ((strtolower($v2['label']) == strtolower(trim($v1))) ||
912 (strtolower($v2['value']) == strtolower(trim($v1)))
914 if ($htmlType == 'CheckBox') {
915 $params[$key][$v2['value']] = $formatted[$key][$v2['value']] = 1;
918 $params[$key][] = $formatted[$key][] = $v2['value'];
929 if (!empty($key) && ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($key)) && array_key_exists($customFieldID, $customFields) &&
930 !array_key_exists($customFieldID, $addressCustomFields)
932 // @todo calling api functions directly is not supported
933 _civicrm_api3_custom_format_params($params, $formatted, $extends);
936 // to check if not update mode and unset the fields with empty value.
937 if (!$this->_updateWithId
&& array_key_exists('custom', $formatted)) {
938 foreach ($formatted['custom'] as $customKey => $customvalue) {
939 if (empty($formatted['custom'][$customKey][-1]['is_required'])) {
940 $formatted['custom'][$customKey][-1]['is_required'] = $customFields[$customKey]['is_required'];
942 $emptyValue = CRM_Utils_Array
::value('value', $customvalue[-1]);
943 if (!isset($emptyValue)) {
944 unset($formatted['custom'][$customKey]);
949 // parse street address, CRM-5450
950 if ($this->_parseStreetAddress
) {
951 if (array_key_exists('address', $formatted) && is_array($formatted['address'])) {
952 foreach ($formatted['address'] as $instance => & $address) {
953 $streetAddress = CRM_Utils_Array
::value('street_address', $address);
954 if (empty($streetAddress)) {
957 // parse address field.
958 $parsedFields = CRM_Core_BAO_Address
::parseStreetAddress($streetAddress);
960 //street address consider to be parsed properly,
961 //If we get street_name and street_number.
962 if (empty($parsedFields['street_name']) ||
empty($parsedFields['street_number'])) {
963 $parsedFields = array_fill_keys(array_keys($parsedFields), '');
966 // merge parse address w/ main address block.
967 $address = array_merge($address, $parsedFields);
974 * Format contact parameters.
976 * @todo this function needs re-writing & re-merging into the main function.
980 * @param array $values
981 * @param array $params
985 protected function formatContactParameters(&$values, &$params) {
986 // Crawl through the possible classes:
999 // Cache the various object fields
1000 static $fields = [];
1002 // first add core contact values since for other Civi modules they are not added
1003 $contactFields = CRM_Contact_DAO_Contact
::fields();
1004 _civicrm_api3_store_values($contactFields, $values, $params);
1006 if (isset($values['contact_type'])) {
1007 // we're an individual/household/org property
1009 $fields[$values['contact_type']] = CRM_Contact_DAO_Contact
::fields();
1011 _civicrm_api3_store_values($fields[$values['contact_type']], $values, $params);
1015 if (isset($values['individual_prefix'])) {
1016 if (!empty($params['prefix_id'])) {
1017 $prefixes = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id');
1018 $params['prefix'] = $prefixes[$params['prefix_id']];
1021 $params['prefix'] = $values['individual_prefix'];
1026 if (isset($values['individual_suffix'])) {
1027 if (!empty($params['suffix_id'])) {
1028 $suffixes = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id');
1029 $params['suffix'] = $suffixes[$params['suffix_id']];
1032 $params['suffix'] = $values['individual_suffix'];
1038 if (isset($values['email_greeting'])) {
1039 if (!empty($params['email_greeting_id'])) {
1040 $emailGreetingFilter = [
1041 'contact_type' => CRM_Utils_Array
::value('contact_type', $params),
1042 'greeting_type' => 'email_greeting',
1044 $emailGreetings = CRM_Core_PseudoConstant
::greeting($emailGreetingFilter);
1045 $params['email_greeting'] = $emailGreetings[$params['email_greeting_id']];
1048 $params['email_greeting'] = $values['email_greeting'];
1054 if (isset($values['postal_greeting'])) {
1055 if (!empty($params['postal_greeting_id'])) {
1056 $postalGreetingFilter = [
1057 'contact_type' => CRM_Utils_Array
::value('contact_type', $params),
1058 'greeting_type' => 'postal_greeting',
1060 $postalGreetings = CRM_Core_PseudoConstant
::greeting($postalGreetingFilter);
1061 $params['postal_greeting'] = $postalGreetings[$params['postal_greeting_id']];
1064 $params['postal_greeting'] = $values['postal_greeting'];
1069 if (isset($values['addressee'])) {
1070 if (!empty($params['addressee_id'])) {
1071 $addresseeFilter = [
1072 'contact_type' => CRM_Utils_Array
::value('contact_type', $params),
1073 'greeting_type' => 'addressee',
1075 $addressee = CRM_Core_PseudoConstant
::addressee($addresseeFilter);
1076 $params['addressee'] = $addressee[$params['addressee_id']];
1079 $params['addressee'] = $values['addressee'];
1084 if (isset($values['gender'])) {
1085 if (!empty($params['gender_id'])) {
1086 $genders = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id');
1087 $params['gender'] = $genders[$params['gender_id']];
1090 $params['gender'] = $values['gender'];
1095 if (!empty($values['preferred_communication_method'])) {
1097 $pcm = array_change_key_case(array_flip(CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method')), CASE_LOWER
);
1099 $preffComm = explode(',', $values['preferred_communication_method']);
1100 foreach ($preffComm as $v) {
1101 $v = strtolower(trim($v));
1102 if (array_key_exists($v, $pcm)) {
1103 $comm[$pcm[$v]] = 1;
1107 $params['preferred_communication_method'] = $comm;
1111 // format the website params.
1112 if (!empty($values['url'])) {
1113 static $websiteFields;
1114 if (!is_array($websiteFields)) {
1115 $websiteFields = CRM_Core_DAO_Website
::fields();
1117 if (!array_key_exists('website', $params) ||
1118 !is_array($params['website'])
1120 $params['website'] = [];
1123 $websiteCount = count($params['website']);
1124 _civicrm_api3_store_values($websiteFields, $values,
1125 $params['website'][++
$websiteCount]
1131 // get the formatted location blocks into params - w/ 3.0 format, CRM-4605
1132 if (!empty($values['location_type_id'])) {
1133 return $this->formatLocationBlock($values, $params);
1136 if (isset($values['note'])) {
1138 if (!isset($params['note'])) {
1139 $params['note'] = [];
1141 $noteBlock = count($params['note']) +
1;
1143 $params['note'][$noteBlock] = [];
1144 if (!isset($fields['Note'])) {
1145 $fields['Note'] = CRM_Core_DAO_Note
::fields();
1148 // get the current logged in civicrm user
1149 $session = CRM_Core_Session
::singleton();
1150 $userID = $session->get('userID');
1153 $values['contact_id'] = $userID;
1156 _civicrm_api3_store_values($fields['Note'], $values, $params['note'][$noteBlock]);
1161 // Check for custom field values
1163 if (empty($fields['custom'])) {
1164 $fields['custom'] = &CRM_Core_BAO_CustomField
::getFields(CRM_Utils_Array
::value('contact_type', $values),
1165 FALSE, FALSE, NULL, NULL, FALSE, FALSE, FALSE
1169 foreach ($values as $key => $value) {
1170 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($key)) {
1171 // check if it's a valid custom field id
1173 if (!array_key_exists($customFieldID, $fields['custom'])) {
1174 return civicrm_api3_create_error('Invalid custom field ID');
1177 $params[$key] = $value;
1185 * Format location block ready for importing.
1187 * There is some test coverage for this in CRM_Contact_Import_Parser_ContactTest
1188 * e.g. testImportPrimaryAddress.
1190 * @param array $values
1191 * @param array $params
1195 protected function formatLocationBlock(&$values, &$params) {
1196 if (empty($values['location_type_id'])) {
1203 'openid' => 'OpenID',
1204 'phone_ext' => 'Phone',
1206 foreach ($blockTypes as $blockFieldName => $block) {
1207 if (!array_key_exists($blockFieldName, $values)) {
1211 // block present in value array.
1212 if (!array_key_exists($blockFieldName, $params) ||
!is_array($params[$blockFieldName])) {
1213 $params[$blockFieldName] = [];
1216 $fields[$block] = $this->getMetadataForEntity($block);
1218 $blockCnt = count($params[$blockFieldName]);
1220 // copy value to dao field name.
1221 if ($blockFieldName == 'im') {
1222 $values['name'] = $values[$blockFieldName];
1225 _civicrm_api3_store_values($fields[$block], $values,
1226 $params[$blockFieldName][++
$blockCnt]
1229 if ($values['location_type_id'] === 'Primary') {
1230 if (!empty($params['id'])) {
1231 $primary = civicrm_api3($block, 'get', [
1232 'return' => 'location_type_id',
1233 'contact_id' => $params['id'],
1238 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1239 $values['location_type_id'] = (isset($primary) && $primary['count']) ?
$primary['values'][0]['location_type_id'] : $defaultLocationType->id
;
1240 $values['is_primary'] = 1;
1243 if (empty($params['id']) && ($blockCnt == 1)) {
1244 $params[$blockFieldName][$blockCnt]['is_primary'] = TRUE;
1247 // we only process single block at a time.
1251 // handle address fields.
1252 if (!array_key_exists('address', $params) ||
!is_array($params['address'])) {
1253 $params['address'] = [];
1256 // Note: we doing multiple value formatting here for address custom fields, plus putting into right format.
1257 // The actual formatting (like date, country ..etc) for address custom fields is taken care of while saving
1258 // the address in CRM_Core_BAO_Address::create method
1259 if (!empty($values['location_type_id'])) {
1260 static $customFields = [];
1261 if (empty($customFields)) {
1262 $customFields = CRM_Core_BAO_CustomField
::getFields('Address');
1264 // make a copy of values, as we going to make changes
1265 $newValues = $values;
1266 foreach ($values as $key => $val) {
1267 $customFieldID = CRM_Core_BAO_CustomField
::getKeyID($key);
1268 if ($customFieldID && array_key_exists($customFieldID, $customFields)) {
1270 $htmlType = CRM_Utils_Array
::value('html_type', $customFields[$customFieldID]);
1271 switch ($htmlType) {
1273 case 'Multi-Select':
1275 $mulValues = explode(',', $val);
1276 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldID, TRUE);
1277 $newValues[$key] = [];
1278 foreach ($mulValues as $v1) {
1279 foreach ($customOption as $v2) {
1280 if ((strtolower($v2['label']) == strtolower(trim($v1))) ||
1281 (strtolower($v2['value']) == strtolower(trim($v1)))
1283 if ($htmlType == 'CheckBox') {
1284 $newValues[$key][$v2['value']] = 1;
1287 $newValues[$key][] = $v2['value'];
1297 // consider new values
1298 $values = $newValues;
1301 $fields['Address'] = $this->getMetadataForEntity('Address');
1302 // @todo this is kinda replicated below....
1303 _civicrm_api3_store_values($fields['Address'], $values, $params['address'][$values['location_type_id']]);
1309 'supplemental_address_1',
1310 'supplemental_address_2',
1311 'supplemental_address_3',
1312 'StateProvince.name',
1314 foreach (array_keys($customFields) as $customFieldID) {
1315 $addressFields[] = 'custom_' . $customFieldID;
1318 foreach ($addressFields as $field) {
1319 if (array_key_exists($field, $values)) {
1320 if (!array_key_exists('address', $params)) {
1321 $params['address'] = [];
1323 $params['address'][$values['location_type_id']][$field] = $values[$field];
1327 if ($values['location_type_id'] === 'Primary') {
1328 if (!empty($params['id'])) {
1329 $primary = civicrm_api3('Address', 'get', [
1330 'return' => 'location_type_id',
1331 'contact_id' => $params['id'],
1336 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1337 $params['address'][$values['location_type_id']]['location_type_id'] = (isset($primary) && $primary['count']) ?
$primary['values'][0]['location_type_id'] : $defaultLocationType->id
;
1338 $params['address'][$values['location_type_id']]['is_primary'] = 1;
1345 * Get the field metadata for the relevant entity.
1347 * @param string $entity
1351 protected function getMetadataForEntity($entity) {
1352 if (!isset($this->fieldMetadata
[$entity])) {
1353 $className = "CRM_Core_DAO_$entity";
1354 $this->fieldMetadata
[$entity] = $className::fields();
1356 return $this->fieldMetadata
[$entity];