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 class CRM_Core_BAO_Mapping
extends CRM_Core_DAO_Mapping
{
22 public function __construct() {
23 parent
::__construct();
27 * Fetch object based on array of properties.
29 * @param array $params
30 * (reference ) an assoc array of name/value pairs.
31 * @param array $defaults
32 * (reference ) an assoc array to hold the flattened values.
35 * CRM_Core_DAO_Mapping object on success, otherwise NULL
37 public static function retrieve(&$params, &$defaults) {
38 $mapping = new CRM_Core_DAO_Mapping();
39 $mapping->copyValues($params);
40 if ($mapping->find(TRUE)) {
41 CRM_Core_DAO
::storeValues($mapping, $defaults);
55 public static function del($id) {
56 return (bool) static::deleteRecord(['id' => $id]);
60 * Takes an associative array and creates a contact object.
62 * The function extract all the params it needs to initialize the create a
63 * contact object. the params array could contain additional unused name/value
66 * @param array $params
67 * An array of name/value pairs.
70 * CRM_Core_DAO_Mapper object on success, otherwise NULL
72 public static function add($params) {
73 $mapping = new CRM_Core_DAO_Mapping();
74 $mapping->copyValues($params);
81 * Get the list of mappings for a select or select2 element.
83 * @param string $mappingType
85 * @param bool $select2
89 * Array of mapping names, keyed by id.
91 public static function getMappings($mappingType, $select2 = FALSE) {
92 $result = civicrm_api3('Mapping', 'get', [
93 'mapping_type_id' => $mappingType,
94 'return' => ['name', 'description'],
102 foreach ($result['values'] as $id => $value) {
104 $item = ['id' => $id, 'text' => $value['name']];
105 if (!empty($value['description'])) {
106 $item['description'] = $value['description'];
111 $mapping[$id] = $value['name'];
118 * Get the mappings array, creating if it does not exist.
120 * @param string $mappingType
124 * Array of mapping names, keyed by id.
126 * @throws \CiviCRM_API3_Exception
128 public static function getCreateMappingValues($mappingType) {
130 return CRM_Core_BAO_Mapping
::getMappings($mappingType);
132 catch (CiviCRM_API3_Exception
$e) {
133 // Having a valid mapping_type_id is now enforced. However, rather than error let's
134 // add it. This is required for Multi value which could be done by upgrade script, but
135 // it feels like there could be other instances so this is safer.
136 $errorParams = $e->getExtraParams();
137 if ($errorParams['error_field'] === 'mapping_type_id') {
138 $mappingValues = civicrm_api3('Mapping', 'getoptions', ['field' => 'mapping_type_id']);
139 civicrm_api3('OptionValue', 'create', [
140 'option_group_id' => 'mapping_type',
141 'label' => $mappingType,
142 'name' => $mappingType,
143 'value' => max(array_keys($mappingValues['values'])) +
1,
146 return CRM_Core_BAO_Mapping
::getMappings($mappingType);
153 * Get the mapping fields.
155 * @param int $mappingId
158 * @param bool $addPrimary
159 * Add the key 'Primary' when the field is a location field AND there is
160 * no location type (meaning Primary)?
163 * array of mapping fields
165 public static function getMappingFields($mappingId, $addPrimary = FALSE) {
166 //mapping is to be loaded from database
167 $mapping = new CRM_Core_DAO_MappingField();
168 $mapping->mapping_id
= $mappingId;
169 $mapping->orderBy('column_number');
172 $mappingName = $mappingLocation = $mappingContactType = $mappingPhoneType = [];
173 $mappingImProvider = $mappingRelation = $mappingOperator = $mappingValue = $mappingWebsiteType = [];
174 while ($mapping->fetch()) {
175 $mappingName[$mapping->grouping
][$mapping->column_number
] = $mapping->name
;
176 $mappingContactType[$mapping->grouping
][$mapping->column_number
] = $mapping->contact_type
;
178 if (!empty($mapping->location_type_id
)) {
179 $mappingLocation[$mapping->grouping
][$mapping->column_number
] = $mapping->location_type_id
;
181 elseif ($addPrimary) {
182 if (CRM_Contact_BAO_Contact
::isFieldHasLocationType($mapping->name
)) {
183 $mappingLocation[$mapping->grouping
][$mapping->column_number
] = ts('Primary');
186 $mappingLocation[$mapping->grouping
][$mapping->column_number
] = NULL;
190 if (!empty($mapping->phone_type_id
)) {
191 $mappingPhoneType[$mapping->grouping
][$mapping->column_number
] = $mapping->phone_type_id
;
194 // get IM service provider type id from mapping fields
195 if (!empty($mapping->im_provider_id
)) {
196 $mappingImProvider[$mapping->grouping
][$mapping->column_number
] = $mapping->im_provider_id
;
199 if (!empty($mapping->website_type_id
)) {
200 $mappingWebsiteType[$mapping->grouping
][$mapping->column_number
] = $mapping->website_type_id
;
203 if (!empty($mapping->relationship_type_id
)) {
204 $mappingRelation[$mapping->grouping
][$mapping->column_number
] = "{$mapping->relationship_type_id}_{$mapping->relationship_direction}";
207 if (!empty($mapping->operator
)) {
208 $mappingOperator[$mapping->grouping
][$mapping->column_number
] = $mapping->operator
;
211 if (!empty($mapping->value
)) {
212 $mappingValue[$mapping->grouping
][$mapping->column_number
] = $mapping->value
;
230 * Get un-indexed array of the field values for the given mapping id.
232 * For example if passing a mapping ID & name the returned array would look like
233 * ['First field name', 'second field name']
235 * @param int $mappingID
236 * @param string $fieldName
239 * @throws \CiviCRM_API3_Exception
241 public static function getMappingFieldValues($mappingID, $fieldName) {
242 return array_merge(CRM_Utils_Array
::collect($fieldName, civicrm_api3('MappingField', 'get', ['mapping_id' => $mappingID, 'return' => $fieldName])['values']));
246 * Check Duplicate Mapping Name.
248 * @param string $nameField
250 * @param string $mapTypeId
255 public static function checkMapping($nameField, $mapTypeId) {
256 $mapping = new CRM_Core_DAO_Mapping();
257 $mapping->name
= $nameField;
258 $mapping->mapping_type_id
= $mapTypeId;
259 return (bool) $mapping->find(TRUE);
263 * Function returns associated array of elements, that will be passed for search.
265 * @param int $smartGroupId
269 * associated array of elements
271 public static function getFormattedFields($smartGroupId) {
274 //get the fields from mapping table
275 $dao = new CRM_Core_DAO_MappingField();
276 $dao->mapping_id
= $smartGroupId;
278 while ($dao->fetch()) {
279 $fldName = $dao->name
;
280 if ($dao->location_type_id
) {
281 $fldName .= "-{$dao->location_type_id}";
283 if ($dao->phone_type
) {
284 $fldName .= "-{$dao->phone_type}";
286 $returnFields[$fldName]['value'] = $dao->value
;
287 $returnFields[$fldName]['op'] = $dao->operator
;
288 $returnFields[$fldName]['grouping'] = $dao->grouping
;
290 return $returnFields;
294 * Build the mapping form for Search Builder.
296 * @param CRM_Core_Form $form
297 * @param int $mappingId
298 * @param int $columnNo
299 * @param int $blockCount
300 * (no of blocks shown).
301 * @param int $exportMode
303 public static function buildMappingForm(&$form, $mappingId, $columnNo, $blockCount, $exportMode = NULL) {
305 $hasLocationTypes = [];
306 $hasRelationTypes = [];
308 $columnCount = $columnNo;
309 $form->addElement('xbutton', 'addBlock', ts('Also include contacts where'),
312 'class' => 'submit-link',
317 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypes();
318 $fields = self
::getBasicFields('Search Builder');
320 // Unset groups, tags, notes for component export
321 if ($exportMode != CRM_Export_Form_Select
::CONTACT_EXPORT
) {
322 foreach (array_keys($fields) as $type) {
323 CRM_Utils_Array
::remove($fields[$type], 'groups', 'tags', 'notes');
327 // Build the common contact fields array.
328 $fields['Contact'] = [];
329 foreach ($fields[$contactTypes[0]] as $key => $value) {
330 // If a field exists across all contact types, move it to the "Contact" selector
332 foreach ($contactTypes as $type) {
333 if (!isset($fields[$type][$key])) {
334 $ubiquitious = FALSE;
338 $fields['Contact'][$key] = $value;
339 foreach ($contactTypes as $type) {
340 unset($fields[$type][$key]);
344 if (array_key_exists('note', $fields['Contact'])) {
345 $noteTitle = $fields['Contact']['note']['title'];
346 $fields['Contact']['note']['title'] = $noteTitle . ': ' . ts('Body and Subject');
347 $fields['Contact']['note_body'] = ['title' => $noteTitle . ': ' . ts('Body Only'), 'name' => 'note_body'];
348 $fields['Contact']['note_subject'] = [
349 'title' => $noteTitle . ': ' . ts('Subject Only'),
350 'name' => 'note_subject',
354 // add component fields
355 $compArray = self
::addComponentFields($fields, 'Search Builder', $exportMode);
357 foreach ($fields as $key => $value) {
359 foreach ($value as $key1 => $value1) {
360 //CRM-2676, replacing the conflict for same custom field name from different custom group.
361 $customGroupName = self
::getCustomGroupName($key1);
363 if ($customGroupName) {
364 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $customGroupName . ': ' . $value1['title'];
367 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $value1['title'];
369 if (isset($value1['hasLocationType'])) {
370 $hasLocationTypes[$key][$key1] = $value1['hasLocationType'];
373 if (isset($value1['hasRelationType'])) {
374 $hasRelationTypes[$key][$key1] = $value1['hasRelationType'];
375 unset($relatedMapperFields[$key][$key1]);
379 if (isset($relatedMapperFields[$key]['related'])) {
380 unset($relatedMapperFields[$key]['related']);
384 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
386 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
388 // FIXME: dirty hack to make the default option show up first. This
389 // avoids a mozilla browser bug with defaults on dynamically constructed
391 if ($defaultLocationType) {
392 $defaultLocation = $locationTypes[$defaultLocationType->id
];
393 unset($locationTypes[$defaultLocationType->id
]);
394 $locationTypes = [$defaultLocationType->id
=> $defaultLocation] +
$locationTypes;
397 $locationTypes = [' ' => ts('Primary')] +
$locationTypes;
399 // since we need a hierarchical list to display contact types & subtypes,
400 // this is what we going to display in first selector
401 $contactTypeSelect = CRM_Contact_BAO_ContactType
::getSelectElements(FALSE, FALSE);
402 $contactTypeSelect = ['Contact' => ts('Contacts')] +
$contactTypeSelect;
404 $sel1 = ['' => ts('- select record type -')] +
$contactTypeSelect +
$compArray;
406 foreach ($sel1 as $key => $sel) {
408 // sort everything BUT the contactType which is sorted separately by
409 // an initial commit of CRM-13278 (check ksort above)
410 if (!in_array($key, $contactTypes)) {
411 asort($mapperFields[$key]);
413 $sel2[$key] = ['' => ts('- select field -')] +
$mapperFields[$key];
419 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
420 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
423 foreach ($sel1 as $k => $sel) {
425 foreach ($locationTypes as $key => $value) {
426 if (trim($key) != '') {
427 $sel4[$k]['phone'][$key] = &$phoneTypes;
428 $sel4[$k]['im'][$key] = &$imProviders;
434 foreach ($sel1 as $k => $sel) {
436 foreach ($mapperFields[$k] as $key => $value) {
437 if (isset($hasLocationTypes[$k][$key])) {
438 $sel3[$k][$key] = $locationTypes;
447 // Array for core fields and relationship custom data
448 $relationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
450 //special fields that have location, hack for primary location
453 'supplemental_address_1',
454 'supplemental_address_2',
455 'supplemental_address_3',
458 'postal_code_suffix',
468 if (isset($mappingId)) {
469 list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider,
470 $mappingRelation, $mappingOperator, $mappingValue
471 ) = CRM_Core_BAO_Mapping
::getMappingFields($mappingId);
473 $blkCnt = count($mappingName);
474 if ($blkCnt >= $blockCount) {
475 $blockCount = $blkCnt +
1;
477 for ($x = 1; $x < $blockCount; $x++
) {
478 if (isset($mappingName[$x])) {
479 $colCnt = count($mappingName[$x]);
480 if ($colCnt >= $columnCount[$x]) {
481 $columnCount[$x] = $colCnt;
487 $form->_blockCount
= $blockCount;
488 $form->_columnCount
= $columnCount;
490 $form->set('blockCount', $form->_blockCount
);
491 $form->set('columnCount', $form->_columnCount
);
493 $defaults = $noneArray = $nullArray = [];
495 for ($x = 1; $x < $blockCount; $x++
) {
497 for ($i = 0; $i < $columnCount[$x]; $i++
) {
499 $sel = &$form->addElement('hierselect', "mapper[$x][$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
502 if (isset($mappingId)) {
503 list($mappingName, $defaults, $noneArray, $jsSet) = self
::loadSavedMapping($mappingLocation, $x, $i, $mappingName, $mapperFields, $mappingContactType, $mappingRelation, $specialFields, $mappingPhoneType, $defaults, $noneArray, $mappingImProvider, $mappingOperator, $mappingValue);
505 //Fix for Search Builder
508 $formValues = $form->exportValues();
510 if (empty($formValues)) {
511 // Incremented length for third select box(relationship type)
512 for ($k = 1; $k < $j; $k++
) {
513 $noneArray[] = [$x, $i, $k];
517 if (!empty($formValues['mapper'][$x])) {
518 foreach ($formValues['mapper'][$x] as $value) {
519 for ($k = 1; $k < $j; $k++
) {
520 if (!isset($formValues['mapper'][$x][$i][$k]) ||
521 (!$formValues['mapper'][$x][$i][$k])
523 $noneArray[] = [$x, $i, $k];
526 $nullArray[] = [$x, $i, $k];
532 for ($k = 1; $k < $j; $k++
) {
533 $noneArray[] = [$x, $i, $k];
538 //Fix for Search Builder
539 $sel->setOptions([$sel1, $sel2, $sel3, $sel4]);
541 //CRM -2292, restricted array set
542 $operatorArray = ['' => ts('-operator-')] + CRM_Core_SelectValues
::getSearchBuilderOperators();
544 $form->add('select', "operator[$x][$i]", '', $operatorArray);
545 $form->add('text', "value[$x][$i]", '');
548 $form->addElement('xbutton', "addMore[$x]", ts('Another search field'), [
550 'class' => 'submit-link',
556 $js = "<script type='text/javascript'>\n";
557 $formName = "document.Builder";
558 if (!empty($nullArray)) {
559 $js .= "var nullArray = [";
562 foreach ($nullArray as $element) {
563 $key = "{$element[0]}, {$element[1]}, {$element[2]}";
564 if (!isset($seen[$key])) {
565 $elements[] = "[$key]";
569 $js .= implode(', ', $elements);
572 for (var i=0;i<nullArray.length;i++) {
573 if ( {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'] ) {
574 {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'].style.display = '';
579 if (!empty($noneArray)) {
580 $js .= "var noneArray = [";
583 foreach ($noneArray as $element) {
584 $key = "{$element[0]}, {$element[1]}, {$element[2]}";
585 if (!isset($seen[$key])) {
586 $elements[] = "[$key]";
590 $js .= implode(', ', $elements);
593 for (var i=0;i<noneArray.length;i++) {
594 if ( {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'] ) {
595 {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'].style.display = 'none';
600 $js .= "</script>\n";
602 $form->assign('initHideBoxes', $js);
603 $form->assign('columnCount', $columnCount);
604 $form->assign('blockCount', $blockCount);
605 $form->setDefaults($defaults);
607 $form->setDefaultAction('refresh');
611 * @param string $mappingType
614 public static function getBasicFields($mappingType) {
615 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypes();
617 foreach ($contactTypes as $contactType) {
618 if ($mappingType == 'Search Builder') {
619 // Get multiple custom group fields in this context
620 $contactFields = CRM_Contact_BAO_Contact
::exportableFields($contactType, FALSE, FALSE, FALSE, TRUE);
623 $contactFields = CRM_Contact_BAO_Contact
::exportableFields($contactType, FALSE, TRUE);
625 $contactFields = array_merge($contactFields, CRM_Contact_BAO_Query_Hook
::singleton()->getFields());
627 // Exclude the address options disabled in the Address Settings
628 $fields[$contactType] = CRM_Core_BAO_Address
::validateAddressOptions($contactFields);
629 ksort($fields[$contactType]);
630 if ($mappingType == 'Export') {
632 $relationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, $contactType);
633 asort($relationshipTypes);
635 foreach ($relationshipTypes as $key => $var) {
636 list($type) = explode('_', $key);
638 $relationships[$key]['title'] = $var;
639 $relationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
640 $relationships[$key]['export'] = TRUE;
641 $relationships[$key]['relationship_type_id'] = $type;
642 $relationships[$key]['related'] = TRUE;
643 $relationships[$key]['hasRelationType'] = 1;
646 if (!empty($relationships)) {
647 $fields[$contactType] = array_merge($fields[$contactType],
648 ['related' => ['title' => ts('- related contact info -')]],
655 // Get the current employer for mapping.
656 if ($mappingType == 'Export') {
657 $fields['Individual']['current_employer_id']['title'] = ts('Current Employer ID');
660 // Contact Sub Type For export
661 $subTypes = CRM_Contact_BAO_ContactType
::subTypeInfo();
662 foreach ($subTypes as $subType => $info) {
663 //adding subtype specific relationships CRM-5256
664 $csRelationships = [];
666 if ($mappingType == 'Export') {
667 $subTypeRelationshipTypes
668 = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, $info['parent'],
669 FALSE, 'label', TRUE, $subType);
671 foreach ($subTypeRelationshipTypes as $key => $var) {
672 if (!array_key_exists($key, $fields[$info['parent']])) {
673 list($type) = explode('_', $key);
675 $csRelationships[$key]['title'] = $var;
676 $csRelationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
677 $csRelationships[$key]['export'] = TRUE;
678 $csRelationships[$key]['relationship_type_id'] = $type;
679 $csRelationships[$key]['related'] = TRUE;
680 $csRelationships[$key]['hasRelationType'] = 1;
685 $fields[$subType] = $fields[$info['parent']] +
$csRelationships;
687 //custom fields for sub type
688 $subTypeFields = CRM_Core_BAO_CustomField
::getFieldsForImport($subType);
689 $fields[$subType] +
= $subTypeFields;
696 * Adds component fields to the export fields array; returns list of components.
698 * @param array $fields
699 * @param string $mappingType
700 * @param int $exportMode
703 public static function addComponentFields(&$fields, $mappingType, $exportMode) {
706 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
)) {
707 if (CRM_Core_Permission
::access('CiviContribute')) {
708 $fields['Contribution'] = CRM_Core_DAO
::getExportableFieldsWithPseudoConstants('CRM_Contribute_BAO_Contribution');
709 unset($fields['Contribution']['contribution_contact_id']);
710 $compArray['Contribution'] = ts('Contribution');
714 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
)) {
715 if (CRM_Core_Permission
::access('CiviEvent')) {
716 $fields['Participant'] = CRM_Event_BAO_Participant
::exportableFields();
717 //get the component payment fields
718 // @todo - review this - inconsistent with other entities & hacky.
719 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
720 $componentPaymentFields = [];
722 'componentPaymentField_total_amount' => ts('Total Amount'),
723 'componentPaymentField_contribution_status' => ts('Contribution Status'),
724 'componentPaymentField_received_date' => ts('Date Received'),
725 'componentPaymentField_payment_instrument' => ts('Payment Method'),
726 'componentPaymentField_transaction_id' => ts('Transaction ID'),
727 ] as $payField => $payTitle) {
728 $componentPaymentFields[$payField] = ['title' => $payTitle];
730 $fields['Participant'] = array_merge($fields['Participant'], $componentPaymentFields);
733 $compArray['Participant'] = ts('Participant');
737 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
)) {
738 if (CRM_Core_Permission
::access('CiviMember')) {
739 $fields['Membership'] = CRM_Member_BAO_Membership
::getMembershipFields($exportMode);
740 unset($fields['Membership']['membership_contact_id']);
741 $compArray['Membership'] = ts('Membership');
745 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
)) {
746 if (CRM_Core_Permission
::access('CiviPledge')) {
747 $fields['Pledge'] = CRM_Pledge_BAO_Pledge
::exportableFields();
748 unset($fields['Pledge']['pledge_contact_id']);
749 $compArray['Pledge'] = ts('Pledge');
753 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
)) {
754 if (CRM_Core_Permission
::access('CiviCase')) {
755 $fields['Case'] = CRM_Case_BAO_Case
::exportableFields();
756 $compArray['Case'] = ts('Case');
758 $fields['Activity'] = CRM_Activity_BAO_Activity
::exportableFields('Case');
759 $compArray['Activity'] = ts('Case Activity');
761 unset($fields['Case']['case_contact_id']);
764 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
)) {
765 if (CRM_Core_Permission
::access('CiviGrant')) {
766 $fields['Grant'] = CRM_Grant_BAO_Grant
::exportableFields();
767 unset($fields['Grant']['grant_contact_id']);
768 if ($mappingType == 'Search Builder') {
769 unset($fields['Grant']['grant_type_id']);
771 $compArray['Grant'] = ts('Grant');
775 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
)) {
776 $fields['Activity'] = CRM_Activity_BAO_Activity
::exportableFields('Activity');
777 $compArray['Activity'] = ts('Activity');
784 * Get the parameters for a mapping field in a saveable format from the quickform mapping format.
786 * @param array $defaults
791 public static function getMappingParams($defaults, $v) {
792 $locationTypeId = NULL;
793 $saveMappingFields = $defaults;
795 $saveMappingFields['name'] = $v['1'] ??
NULL;
796 $saveMappingFields['contact_type'] = $v['0'] ??
NULL;
797 $locationId = $v['2'] ??
NULL;
798 $saveMappingFields['location_type_id'] = is_numeric($locationId) ?
$locationId : NULL;
800 if ($v[1] == 'phone') {
801 $saveMappingFields['phone_type_id'] = $v['3'] ??
NULL;
803 elseif ($v[1] == 'im') {
804 $saveMappingFields['im_provider_id'] = $v['3'] ??
NULL;
807 // Handle mapping for 'related contact' fields
808 if (count(explode('_', CRM_Utils_Array
::value('1', $v))) > 2) {
809 list($id, $first, $second) = explode('_', CRM_Utils_Array
::value('1', $v));
810 if (($first == 'a' && $second == 'b') ||
($first == 'b' && $second == 'a')) {
812 if (!empty($v['2'])) {
813 $saveMappingFields['name'] = $v['2'] ??
NULL;
815 elseif (!empty($v['4'])) {
816 $saveMappingFields['name'] = $v['4'] ??
NULL;
819 if (is_numeric(CRM_Utils_Array
::value('3', $v))) {
820 $locationTypeId = $v['3'] ??
NULL;
822 elseif (is_numeric(CRM_Utils_Array
::value('5', $v))) {
823 $locationTypeId = $v['5'] ??
NULL;
826 if (is_numeric(CRM_Utils_Array
::value('4', $v))) {
827 if ($saveMappingFields['name'] === 'im') {
828 $saveMappingFields['im_provider_id'] = $v[4];
831 $saveMappingFields['phone_type_id'] = $v['4'] ??
NULL;
834 elseif (is_numeric(CRM_Utils_Array
::value('6', $v))) {
835 $saveMappingFields['phone_type_id'] = $v['6'] ??
NULL;
838 $saveMappingFields['location_type_id'] = is_numeric($locationTypeId) ?
$locationTypeId : NULL;
839 $saveMappingFields['relationship_type_id'] = $id;
840 $saveMappingFields['relationship_direction'] = "{$first}_{$second}";
844 return $saveMappingFields;
848 * Load saved mapping.
850 * @param $mappingLocation
853 * @param $mappingName
854 * @param $mapperFields
855 * @param $mappingContactType
856 * @param $mappingRelation
857 * @param array $specialFields
858 * @param $mappingPhoneType
860 * @param array $defaults
861 * @param array $noneArray
863 * @param $mappingImProvider
864 * @param $mappingOperator
865 * @param $mappingValue
869 protected static function loadSavedMapping($mappingLocation, int $x, int $i, $mappingName, $mapperFields, $mappingContactType, $mappingRelation, array $specialFields, $mappingPhoneType, array $defaults, array $noneArray, $mappingImProvider, $mappingOperator, $mappingValue) {
871 $locationId = $mappingLocation[$x][$i] ??
0;
872 if (isset($mappingName[$x][$i])) {
873 if (is_array($mapperFields[$mappingContactType[$x][$i]])) {
875 if (isset($mappingRelation[$x][$i])) {
876 $relLocationId = $mappingLocation[$x][$i] ??
0;
877 if (!$relLocationId && in_array($mappingName[$x][$i], $specialFields)) {
878 $relLocationId = " ";
881 $relPhoneType = $mappingPhoneType[$x][$i] ??
NULL;
883 $defaults["mapper[$x][$i]"] = [
884 $mappingContactType[$x][$i],
885 $mappingRelation[$x][$i],
888 $mappingName[$x][$i],
894 $noneArray[] = [$x, $i, 2];
896 if (!$phoneType && !$imProvider) {
897 $noneArray[] = [$x, $i, 3];
899 if (!$mappingName[$x][$i]) {
900 $noneArray[] = [$x, $i, 4];
902 if (!$relLocationId) {
903 $noneArray[] = [$x, $i, 5];
905 if (!$relPhoneType) {
906 $noneArray[] = [$x, $i, 6];
908 $noneArray[] = [$x, $i, 2];
911 $phoneType = $mappingPhoneType[$x][$i] ??
NULL;
912 $imProvider = $mappingImProvider[$x][$i] ??
NULL;
913 if (!$locationId && in_array($mappingName[$x][$i], $specialFields)) {
917 $defaults["mapper[$x][$i]"] = [
918 $mappingContactType[$x][$i],
919 $mappingName[$x][$i],
923 if (!$mappingName[$x][$i]) {
924 $noneArray[] = [$x, $i, 1];
927 $noneArray[] = [$x, $i, 2];
929 if (!$phoneType && !$imProvider) {
930 $noneArray[] = [$x, $i, 3];
933 $noneArray[] = [$x, $i, 4];
934 $noneArray[] = [$x, $i, 5];
935 $noneArray[] = [$x, $i, 6];
940 if (CRM_Utils_Array
::value($i, CRM_Utils_Array
::value($x, $mappingOperator))) {
941 $defaults["operator[$x][$i]"] = $mappingOperator[$x][$i] ??
NULL;
944 if (CRM_Utils_Array
::value($i, CRM_Utils_Array
::value($x, $mappingValue))) {
945 $defaults["value[$x][$i]"] = $mappingValue[$x][$i] ??
NULL;
949 return [$mappingName, $defaults, $noneArray, $jsSet];
953 * Function returns all custom fields with group title and
956 * @param int $relationshipTypeId
957 * Related relationship type id.
960 * all custom field titles
962 public function getRelationTypeCustomGroupData($relationshipTypeId) {
964 $customFields = CRM_Core_BAO_CustomField
::getFields('Relationship', NULL, NULL, $relationshipTypeId, NULL, NULL);
966 foreach ($customFields as $krelation => $vrelation) {
967 $groupTitle[$vrelation['label']] = $vrelation['groupTitle'] . '...' . $vrelation['label'];
973 * Function returns all Custom group Names.
975 * @param int $customfieldId
978 * @return null|string
979 * $customGroupName all custom group names
981 public static function getCustomGroupName($customfieldId) {
982 if ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($customfieldId)) {
983 $customGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $customFieldId, 'custom_group_id');
984 $customGroupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'title');
986 $customGroupName = CRM_Utils_String
::ellipsify($customGroupName, 13);
988 return $customGroupName;
993 * Function returns associated array of elements, that will be passed for search
995 * @param array $params
996 * Associated array of submitted values.
998 * Row no of the fields.
1002 * formatted associated array of elements
1003 * @throws CRM_Core_Exception
1005 public static function formattedFields(&$params, $row = FALSE) {
1008 if (empty($params) ||
!isset($params['mapper'])) {
1012 $types = ['Individual', 'Organization', 'Household'];
1013 foreach ($params['mapper'] as $key => $value) {
1014 $contactType = NULL;
1015 foreach ($value as $k => $v) {
1016 if (in_array($v[0], $types)) {
1017 if ($contactType && $contactType != $v[0]) {
1018 throw new CRM_Core_Exception(ts("Cannot have two clauses with different types: %1, %2",
1019 [1 => $contactType, 2 => $v[0]]
1022 $contactType = $v[0];
1024 if (!empty($v['1'])) {
1026 $v2 = $v['2'] ??
NULL;
1027 if ($v2 && trim($v2)) {
1028 $fldName .= "-{$v[2]}";
1031 $v3 = $v['3'] ??
NULL;
1032 if ($v3 && trim($v3)) {
1033 $fldName .= "-{$v[3]}";
1036 $value = $params['value'][$key][$k];
1038 if ($v[0] == 'Contribution' && substr($fldName, 0, 7) != 'custom_'
1039 && substr($fldName, 0, 10) != 'financial_'
1040 && substr($fldName, 0, 8) != 'payment_') {
1041 if (substr($fldName, 0, 13) != 'contribution_') {
1042 $fldName = 'contribution_' . $fldName;
1046 // CRM-14983: verify if values are comma separated convert to array
1047 if (!is_array($value) && strstr($params['operator'][$key][$k], 'IN')) {
1048 $value = explode(',', $value);
1049 $value = [$params['operator'][$key][$k] => $value];
1051 // CRM-19081 Fix legacy StateProvince Field Values.
1052 // These derive from smart groups created using search builder under older
1053 // CiviCRM versions.
1054 if (!is_numeric($value) && $fldName == 'state_province') {
1055 $value = CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Address', 'state_province_id', $value);
1061 $params['operator'][$key][$k],
1070 $params['operator'][$key][$k],
1089 //add sortByCharacter values
1090 if (isset($params['sortByCharacter'])) {
1094 $params['sortByCharacter'],
1103 * @param array $params
1107 public static function &returnProperties(&$params) {
1109 'contact_type' => 1,
1110 'contact_sub_type' => 1,
1114 if (empty($params) ||
empty($params['mapper'])) {
1118 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
1119 foreach ($params['mapper'] as $key => $value) {
1120 foreach ($value as $k => $v) {
1122 if ($v[1] == 'groups' ||
$v[1] == 'tags') {
1126 if (isset($v[2]) && is_numeric($v[2])) {
1127 if (!array_key_exists('location', $fields)) {
1128 $fields['location'] = [];
1131 // make sure that we have a location fields and a location type for this
1132 $locationName = $locationTypes[$v[2]];
1133 if (!array_key_exists($locationName, $fields['location'])) {
1134 $fields['location'][$locationName] = [];
1135 $fields['location'][$locationName]['location_type'] = $v[2];
1138 if ($v[1] == 'phone' ||
$v[1] == 'email' ||
$v[1] == 'im') {
1139 // phone type handling
1141 $fields['location'][$locationName][$v[1] . "-" . $v[3]] = 1;
1144 $fields['location'][$locationName][$v[1]] = 1;
1148 $fields['location'][$locationName][$v[1]] = 1;
1162 * Save the mapping field info for search builder / export given the formvalues
1164 * @param array $params
1165 * Asscociated array of formvalues.
1166 * @param int $mappingId
1171 public static function saveMappingFields($params, $mappingId) {
1172 //delete mapping fields records for existing mapping
1173 $mappingFields = new CRM_Core_DAO_MappingField();
1174 $mappingFields->mapping_id
= $mappingId;
1175 $mappingFields->delete();
1177 if (empty($params['mapper'])) {
1181 //save record in mapping field table
1182 foreach ($params['mapper'] as $key => $value) {
1184 foreach ($value as $k => $v) {
1186 if (!empty($v['1'])) {
1187 $saveMappingParams = self
::getMappingParams(
1189 'mapping_id' => $mappingId,
1191 'operator' => $params['operator'][$key][$k] ??
NULL,
1192 'value' => $params['value'][$key][$k] ??
NULL,
1193 'column_number' => $colCnt,
1195 $saveMappingField = new CRM_Core_DAO_MappingField();
1196 $saveMappingField->copyValues($saveMappingParams);
1197 $saveMappingField->save();
1205 * Remove references to a specific field from save Mappings
1206 * @param string $fieldName
1208 public static function removeFieldFromMapping($fieldName): void
{
1209 $mappingField = new CRM_Core_DAO_MappingField();
1210 $mappingField->name
= $fieldName;
1211 $mappingField->delete();