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 // delete from mapping_field table
57 $mappingField = new CRM_Core_DAO_MappingField();
58 $mappingField->mapping_id
= $id;
59 $mappingField->delete();
61 // delete from mapping table
62 $mapping = new CRM_Core_DAO_Mapping();
64 if ($mapping->find(TRUE)) {
65 $result = $mapping->delete();
72 * Takes an associative array and creates a contact object.
74 * The function extract all the params it needs to initialize the create a
75 * contact object. the params array could contain additional unused name/value
78 * @param array $params
79 * An array of name/value pairs.
82 * CRM_Core_DAO_Mapper object on success, otherwise NULL
84 public static function add($params) {
85 $mapping = new CRM_Core_DAO_Mapping();
86 $mapping->copyValues($params);
93 * Get the list of mappings for a select or select2 element.
95 * @param string $mappingType
97 * @param bool $select2
101 * Array of mapping names, keyed by id.
103 public static function getMappings($mappingType, $select2 = FALSE) {
104 $result = civicrm_api3('Mapping', 'get', [
105 'mapping_type_id' => $mappingType,
106 'return' => ['name', 'description'],
114 foreach ($result['values'] as $id => $value) {
116 $item = ['id' => $id, 'text' => $value['name']];
117 if (!empty($value['description'])) {
118 $item['description'] = $value['description'];
123 $mapping[$id] = $value['name'];
130 * Get the mappings array, creating if it does not exist.
132 * @param string $mappingType
136 * Array of mapping names, keyed by id.
138 * @throws \CiviCRM_API3_Exception
140 public static function getCreateMappingValues($mappingType) {
142 return CRM_Core_BAO_Mapping
::getMappings($mappingType);
144 catch (CiviCRM_API3_Exception
$e) {
145 // Having a valid mapping_type_id is now enforced. However, rather than error let's
146 // add it. This is required for Multi value which could be done by upgrade script, but
147 // it feels like there could be other instances so this is safer.
148 $errorParams = $e->getExtraParams();
149 if ($errorParams['error_field'] === 'mapping_type_id') {
150 $mappingValues = civicrm_api3('Mapping', 'getoptions', ['field' => 'mapping_type_id']);
151 civicrm_api3('OptionValue', 'create', [
152 'option_group_id' => 'mapping_type',
153 'label' => $mappingType,
154 'name' => $mappingType,
155 'value' => max(array_keys($mappingValues['values'])) +
1,
158 return CRM_Core_BAO_Mapping
::getMappings($mappingType);
165 * Get the mapping fields.
167 * @param int $mappingId
170 * @param bool $addPrimary
171 * Add the key 'Primary' when the field is a location field AND there is
172 * no location type (meaning Primary)?
175 * array of mapping fields
177 public static function getMappingFields($mappingId, $addPrimary = FALSE) {
178 //mapping is to be loaded from database
179 $mapping = new CRM_Core_DAO_MappingField();
180 $mapping->mapping_id
= $mappingId;
181 $mapping->orderBy('column_number');
184 $mappingName = $mappingLocation = $mappingContactType = $mappingPhoneType = [];
185 $mappingImProvider = $mappingRelation = $mappingOperator = $mappingValue = $mappingWebsiteType = [];
186 while ($mapping->fetch()) {
187 $mappingName[$mapping->grouping
][$mapping->column_number
] = $mapping->name
;
188 $mappingContactType[$mapping->grouping
][$mapping->column_number
] = $mapping->contact_type
;
190 if (!empty($mapping->location_type_id
)) {
191 $mappingLocation[$mapping->grouping
][$mapping->column_number
] = $mapping->location_type_id
;
193 elseif ($addPrimary) {
194 if (CRM_Contact_BAO_Contact
::isFieldHasLocationType($mapping->name
)) {
195 $mappingLocation[$mapping->grouping
][$mapping->column_number
] = ts('Primary');
198 $mappingLocation[$mapping->grouping
][$mapping->column_number
] = NULL;
202 if (!empty($mapping->phone_type_id
)) {
203 $mappingPhoneType[$mapping->grouping
][$mapping->column_number
] = $mapping->phone_type_id
;
206 // get IM service provider type id from mapping fields
207 if (!empty($mapping->im_provider_id
)) {
208 $mappingImProvider[$mapping->grouping
][$mapping->column_number
] = $mapping->im_provider_id
;
211 if (!empty($mapping->website_type_id
)) {
212 $mappingWebsiteType[$mapping->grouping
][$mapping->column_number
] = $mapping->website_type_id
;
215 if (!empty($mapping->relationship_type_id
)) {
216 $mappingRelation[$mapping->grouping
][$mapping->column_number
] = "{$mapping->relationship_type_id}_{$mapping->relationship_direction}";
219 if (!empty($mapping->operator
)) {
220 $mappingOperator[$mapping->grouping
][$mapping->column_number
] = $mapping->operator
;
223 if (!empty($mapping->value
)) {
224 $mappingValue[$mapping->grouping
][$mapping->column_number
] = $mapping->value
;
242 * Get un-indexed array of the field values for the given mapping id.
244 * For example if passing a mapping ID & name the returned array would look like
245 * ['First field name', 'second field name']
247 * @param int $mappingID
248 * @param string $fieldName
251 * @throws \CiviCRM_API3_Exception
253 public static function getMappingFieldValues($mappingID, $fieldName) {
254 return array_merge(CRM_Utils_Array
::collect($fieldName, civicrm_api3('MappingField', 'get', ['mapping_id' => $mappingID, 'return' => $fieldName])['values']));
258 * Check Duplicate Mapping Name.
260 * @param string $nameField
262 * @param string $mapTypeId
267 public static function checkMapping($nameField, $mapTypeId) {
268 $mapping = new CRM_Core_DAO_Mapping();
269 $mapping->name
= $nameField;
270 $mapping->mapping_type_id
= $mapTypeId;
271 return (bool) $mapping->find(TRUE);
275 * Function returns associated array of elements, that will be passed for search.
277 * @param int $smartGroupId
281 * associated array of elements
283 public static function getFormattedFields($smartGroupId) {
286 //get the fields from mapping table
287 $dao = new CRM_Core_DAO_MappingField();
288 $dao->mapping_id
= $smartGroupId;
290 while ($dao->fetch()) {
291 $fldName = $dao->name
;
292 if ($dao->location_type_id
) {
293 $fldName .= "-{$dao->location_type_id}";
295 if ($dao->phone_type
) {
296 $fldName .= "-{$dao->phone_type}";
298 $returnFields[$fldName]['value'] = $dao->value
;
299 $returnFields[$fldName]['op'] = $dao->operator
;
300 $returnFields[$fldName]['grouping'] = $dao->grouping
;
302 return $returnFields;
306 * Build the mapping form for Search Builder.
308 * @param CRM_Core_Form $form
309 * @param int $mappingId
310 * @param int $columnNo
311 * @param int $blockCount
312 * (no of blocks shown).
313 * @param int $exportMode
315 public static function buildMappingForm(&$form, $mappingId, $columnNo, $blockCount, $exportMode = NULL) {
317 $hasLocationTypes = [];
318 $hasRelationTypes = [];
320 $columnCount = $columnNo;
321 $form->addElement('xbutton', 'addBlock', ts('Also include contacts where'),
324 'class' => 'submit-link',
329 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypes();
330 $fields = self
::getBasicFields('Search Builder');
332 // Unset groups, tags, notes for component export
333 if ($exportMode != CRM_Export_Form_Select
::CONTACT_EXPORT
) {
334 foreach (array_keys($fields) as $type) {
335 CRM_Utils_Array
::remove($fields[$type], 'groups', 'tags', 'notes');
339 // Build the common contact fields array.
340 $fields['Contact'] = [];
341 foreach ($fields[$contactTypes[0]] as $key => $value) {
342 // If a field exists across all contact types, move it to the "Contact" selector
344 foreach ($contactTypes as $type) {
345 if (!isset($fields[$type][$key])) {
346 $ubiquitious = FALSE;
350 $fields['Contact'][$key] = $value;
351 foreach ($contactTypes as $type) {
352 unset($fields[$type][$key]);
356 if (array_key_exists('note', $fields['Contact'])) {
357 $noteTitle = $fields['Contact']['note']['title'];
358 $fields['Contact']['note']['title'] = $noteTitle . ': ' . ts('Body and Subject');
359 $fields['Contact']['note_body'] = ['title' => $noteTitle . ': ' . ts('Body Only'), 'name' => 'note_body'];
360 $fields['Contact']['note_subject'] = [
361 'title' => $noteTitle . ': ' . ts('Subject Only'),
362 'name' => 'note_subject',
366 // add component fields
367 $compArray = self
::addComponentFields($fields, 'Search Builder', $exportMode);
369 foreach ($fields as $key => $value) {
371 foreach ($value as $key1 => $value1) {
372 //CRM-2676, replacing the conflict for same custom field name from different custom group.
373 $customGroupName = self
::getCustomGroupName($key1);
375 if ($customGroupName) {
376 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $customGroupName . ': ' . $value1['title'];
379 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $value1['title'];
381 if (isset($value1['hasLocationType'])) {
382 $hasLocationTypes[$key][$key1] = $value1['hasLocationType'];
385 if (isset($value1['hasRelationType'])) {
386 $hasRelationTypes[$key][$key1] = $value1['hasRelationType'];
387 unset($relatedMapperFields[$key][$key1]);
391 if (isset($relatedMapperFields[$key]['related'])) {
392 unset($relatedMapperFields[$key]['related']);
396 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
398 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
400 // FIXME: dirty hack to make the default option show up first. This
401 // avoids a mozilla browser bug with defaults on dynamically constructed
403 if ($defaultLocationType) {
404 $defaultLocation = $locationTypes[$defaultLocationType->id
];
405 unset($locationTypes[$defaultLocationType->id
]);
406 $locationTypes = [$defaultLocationType->id
=> $defaultLocation] +
$locationTypes;
409 $locationTypes = [' ' => ts('Primary')] +
$locationTypes;
411 // since we need a hierarchical list to display contact types & subtypes,
412 // this is what we going to display in first selector
413 $contactTypeSelect = CRM_Contact_BAO_ContactType
::getSelectElements(FALSE, FALSE);
414 $contactTypeSelect = ['Contact' => ts('Contacts')] +
$contactTypeSelect;
416 $sel1 = ['' => ts('- select record type -')] +
$contactTypeSelect +
$compArray;
418 foreach ($sel1 as $key => $sel) {
420 // sort everything BUT the contactType which is sorted separately by
421 // an initial commit of CRM-13278 (check ksort above)
422 if (!in_array($key, $contactTypes)) {
423 asort($mapperFields[$key]);
425 $sel2[$key] = ['' => ts('- select field -')] +
$mapperFields[$key];
431 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
432 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
435 foreach ($sel1 as $k => $sel) {
437 foreach ($locationTypes as $key => $value) {
438 if (trim($key) != '') {
439 $sel4[$k]['phone'][$key] = &$phoneTypes;
440 $sel4[$k]['im'][$key] = &$imProviders;
446 foreach ($sel1 as $k => $sel) {
448 foreach ($mapperFields[$k] as $key => $value) {
449 if (isset($hasLocationTypes[$k][$key])) {
450 $sel3[$k][$key] = $locationTypes;
459 // Array for core fields and relationship custom data
460 $relationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
462 //special fields that have location, hack for primary location
465 'supplemental_address_1',
466 'supplemental_address_2',
467 'supplemental_address_3',
470 'postal_code_suffix',
480 if (isset($mappingId)) {
481 list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider,
482 $mappingRelation, $mappingOperator, $mappingValue
483 ) = CRM_Core_BAO_Mapping
::getMappingFields($mappingId);
485 $blkCnt = count($mappingName);
486 if ($blkCnt >= $blockCount) {
487 $blockCount = $blkCnt +
1;
489 for ($x = 1; $x < $blockCount; $x++
) {
490 if (isset($mappingName[$x])) {
491 $colCnt = count($mappingName[$x]);
492 if ($colCnt >= $columnCount[$x]) {
493 $columnCount[$x] = $colCnt;
499 $form->_blockCount
= $blockCount;
500 $form->_columnCount
= $columnCount;
502 $form->set('blockCount', $form->_blockCount
);
503 $form->set('columnCount', $form->_columnCount
);
505 $defaults = $noneArray = $nullArray = [];
507 for ($x = 1; $x < $blockCount; $x++
) {
509 for ($i = 0; $i < $columnCount[$x]; $i++
) {
511 $sel = &$form->addElement('hierselect', "mapper[$x][$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
514 if (isset($mappingId)) {
515 list($mappingName, $defaults, $noneArray, $jsSet) = self
::loadSavedMapping($mappingLocation, $x, $i, $mappingName, $mapperFields, $mappingContactType, $mappingRelation, $specialFields, $mappingPhoneType, $defaults, $noneArray, $mappingImProvider, $mappingOperator, $mappingValue);
517 //Fix for Search Builder
520 $formValues = $form->exportValues();
522 if (empty($formValues)) {
523 // Incremented length for third select box(relationship type)
524 for ($k = 1; $k < $j; $k++
) {
525 $noneArray[] = [$x, $i, $k];
529 if (!empty($formValues['mapper'][$x])) {
530 foreach ($formValues['mapper'][$x] as $value) {
531 for ($k = 1; $k < $j; $k++
) {
532 if (!isset($formValues['mapper'][$x][$i][$k]) ||
533 (!$formValues['mapper'][$x][$i][$k])
535 $noneArray[] = [$x, $i, $k];
538 $nullArray[] = [$x, $i, $k];
544 for ($k = 1; $k < $j; $k++
) {
545 $noneArray[] = [$x, $i, $k];
550 //Fix for Search Builder
551 $sel->setOptions([$sel1, $sel2, $sel3, $sel4]);
553 //CRM -2292, restricted array set
554 $operatorArray = ['' => ts('-operator-')] + CRM_Core_SelectValues
::getSearchBuilderOperators();
556 $form->add('select', "operator[$x][$i]", '', $operatorArray);
557 $form->add('text', "value[$x][$i]", '');
560 $form->addElement('xbutton', "addMore[$x]", ts('Another search field'), [
562 'class' => 'submit-link',
568 $js = "<script type='text/javascript'>\n";
569 $formName = "document.Builder";
570 if (!empty($nullArray)) {
571 $js .= "var nullArray = [";
574 foreach ($nullArray as $element) {
575 $key = "{$element[0]}, {$element[1]}, {$element[2]}";
576 if (!isset($seen[$key])) {
577 $elements[] = "[$key]";
581 $js .= implode(', ', $elements);
584 for (var i=0;i<nullArray.length;i++) {
585 if ( {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'] ) {
586 {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'].style.display = '';
591 if (!empty($noneArray)) {
592 $js .= "var noneArray = [";
595 foreach ($noneArray as $element) {
596 $key = "{$element[0]}, {$element[1]}, {$element[2]}";
597 if (!isset($seen[$key])) {
598 $elements[] = "[$key]";
602 $js .= implode(', ', $elements);
605 for (var i=0;i<noneArray.length;i++) {
606 if ( {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'] ) {
607 {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'].style.display = 'none';
612 $js .= "</script>\n";
614 $form->assign('initHideBoxes', $js);
615 $form->assign('columnCount', $columnCount);
616 $form->assign('blockCount', $blockCount);
617 $form->setDefaults($defaults);
619 $form->setDefaultAction('refresh');
623 * @param string $mappingType
626 public static function getBasicFields($mappingType) {
627 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypes();
629 foreach ($contactTypes as $contactType) {
630 if ($mappingType == 'Search Builder') {
631 // Get multiple custom group fields in this context
632 $contactFields = CRM_Contact_BAO_Contact
::exportableFields($contactType, FALSE, FALSE, FALSE, TRUE);
635 $contactFields = CRM_Contact_BAO_Contact
::exportableFields($contactType, FALSE, TRUE);
637 $contactFields = array_merge($contactFields, CRM_Contact_BAO_Query_Hook
::singleton()->getFields());
639 // Exclude the address options disabled in the Address Settings
640 $fields[$contactType] = CRM_Core_BAO_Address
::validateAddressOptions($contactFields);
641 ksort($fields[$contactType]);
642 if ($mappingType == 'Export') {
644 $relationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, $contactType);
645 asort($relationshipTypes);
647 foreach ($relationshipTypes as $key => $var) {
648 list($type) = explode('_', $key);
650 $relationships[$key]['title'] = $var;
651 $relationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
652 $relationships[$key]['export'] = TRUE;
653 $relationships[$key]['relationship_type_id'] = $type;
654 $relationships[$key]['related'] = TRUE;
655 $relationships[$key]['hasRelationType'] = 1;
658 if (!empty($relationships)) {
659 $fields[$contactType] = array_merge($fields[$contactType],
660 ['related' => ['title' => ts('- related contact info -')]],
667 // Get the current employer for mapping.
668 if ($mappingType == 'Export') {
669 $fields['Individual']['current_employer_id']['title'] = ts('Current Employer ID');
672 // Contact Sub Type For export
673 $subTypes = CRM_Contact_BAO_ContactType
::subTypeInfo();
674 foreach ($subTypes as $subType => $info) {
675 //adding subtype specific relationships CRM-5256
676 $csRelationships = [];
678 if ($mappingType == 'Export') {
679 $subTypeRelationshipTypes
680 = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, $info['parent'],
681 FALSE, 'label', TRUE, $subType);
683 foreach ($subTypeRelationshipTypes as $key => $var) {
684 if (!array_key_exists($key, $fields[$info['parent']])) {
685 list($type) = explode('_', $key);
687 $csRelationships[$key]['title'] = $var;
688 $csRelationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
689 $csRelationships[$key]['export'] = TRUE;
690 $csRelationships[$key]['relationship_type_id'] = $type;
691 $csRelationships[$key]['related'] = TRUE;
692 $csRelationships[$key]['hasRelationType'] = 1;
697 $fields[$subType] = $fields[$info['parent']] +
$csRelationships;
699 //custom fields for sub type
700 $subTypeFields = CRM_Core_BAO_CustomField
::getFieldsForImport($subType);
701 $fields[$subType] +
= $subTypeFields;
708 * Adds component fields to the export fields array; returns list of components.
710 * @param array $fields
711 * @param string $mappingType
712 * @param int $exportMode
715 public static function addComponentFields(&$fields, $mappingType, $exportMode) {
718 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
)) {
719 if (CRM_Core_Permission
::access('CiviContribute')) {
720 $fields['Contribution'] = CRM_Core_DAO
::getExportableFieldsWithPseudoConstants('CRM_Contribute_BAO_Contribution');
721 unset($fields['Contribution']['contribution_contact_id']);
722 $compArray['Contribution'] = ts('Contribution');
726 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
)) {
727 if (CRM_Core_Permission
::access('CiviEvent')) {
728 $fields['Participant'] = CRM_Event_BAO_Participant
::exportableFields();
729 //get the component payment fields
730 // @todo - review this - inconsistent with other entities & hacky.
731 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
732 $componentPaymentFields = [];
734 'componentPaymentField_total_amount' => ts('Total Amount'),
735 'componentPaymentField_contribution_status' => ts('Contribution Status'),
736 'componentPaymentField_received_date' => ts('Date Received'),
737 'componentPaymentField_payment_instrument' => ts('Payment Method'),
738 'componentPaymentField_transaction_id' => ts('Transaction ID'),
739 ] as $payField => $payTitle) {
740 $componentPaymentFields[$payField] = ['title' => $payTitle];
742 $fields['Participant'] = array_merge($fields['Participant'], $componentPaymentFields);
745 $compArray['Participant'] = ts('Participant');
749 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
)) {
750 if (CRM_Core_Permission
::access('CiviMember')) {
751 $fields['Membership'] = CRM_Member_BAO_Membership
::getMembershipFields($exportMode);
752 unset($fields['Membership']['membership_contact_id']);
753 $compArray['Membership'] = ts('Membership');
757 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
)) {
758 if (CRM_Core_Permission
::access('CiviPledge')) {
759 $fields['Pledge'] = CRM_Pledge_BAO_Pledge
::exportableFields();
760 unset($fields['Pledge']['pledge_contact_id']);
761 $compArray['Pledge'] = ts('Pledge');
765 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
)) {
766 if (CRM_Core_Permission
::access('CiviCase')) {
767 $fields['Case'] = CRM_Case_BAO_Case
::exportableFields();
768 $compArray['Case'] = ts('Case');
770 $fields['Activity'] = CRM_Activity_BAO_Activity
::exportableFields('Case');
771 $compArray['Activity'] = ts('Case Activity');
773 unset($fields['Case']['case_contact_id']);
776 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
)) {
777 if (CRM_Core_Permission
::access('CiviGrant')) {
778 $fields['Grant'] = CRM_Grant_BAO_Grant
::exportableFields();
779 unset($fields['Grant']['grant_contact_id']);
780 if ($mappingType == 'Search Builder') {
781 unset($fields['Grant']['grant_type_id']);
783 $compArray['Grant'] = ts('Grant');
787 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
)) {
788 $fields['Activity'] = CRM_Activity_BAO_Activity
::exportableFields('Activity');
789 $compArray['Activity'] = ts('Activity');
796 * Get the parameters for a mapping field in a saveable format from the quickform mapping format.
798 * @param array $defaults
803 public static function getMappingParams($defaults, $v) {
804 $locationTypeId = NULL;
805 $saveMappingFields = $defaults;
807 $saveMappingFields['name'] = $v['1'] ??
NULL;
808 $saveMappingFields['contact_type'] = $v['0'] ??
NULL;
809 $locationId = $v['2'] ??
NULL;
810 $saveMappingFields['location_type_id'] = is_numeric($locationId) ?
$locationId : NULL;
812 if ($v[1] == 'phone') {
813 $saveMappingFields['phone_type_id'] = $v['3'] ??
NULL;
815 elseif ($v[1] == 'im') {
816 $saveMappingFields['im_provider_id'] = $v['3'] ??
NULL;
819 // Handle mapping for 'related contact' fields
820 if (count(explode('_', CRM_Utils_Array
::value('1', $v))) > 2) {
821 list($id, $first, $second) = explode('_', CRM_Utils_Array
::value('1', $v));
822 if (($first == 'a' && $second == 'b') ||
($first == 'b' && $second == 'a')) {
824 if (!empty($v['2'])) {
825 $saveMappingFields['name'] = $v['2'] ??
NULL;
827 elseif (!empty($v['4'])) {
828 $saveMappingFields['name'] = $v['4'] ??
NULL;
831 if (is_numeric(CRM_Utils_Array
::value('3', $v))) {
832 $locationTypeId = $v['3'] ??
NULL;
834 elseif (is_numeric(CRM_Utils_Array
::value('5', $v))) {
835 $locationTypeId = $v['5'] ??
NULL;
838 if (is_numeric(CRM_Utils_Array
::value('4', $v))) {
839 if ($saveMappingFields['name'] === 'im') {
840 $saveMappingFields['im_provider_id'] = $v[4];
843 $saveMappingFields['phone_type_id'] = $v['4'] ??
NULL;
846 elseif (is_numeric(CRM_Utils_Array
::value('6', $v))) {
847 $saveMappingFields['phone_type_id'] = $v['6'] ??
NULL;
850 $saveMappingFields['location_type_id'] = is_numeric($locationTypeId) ?
$locationTypeId : NULL;
851 $saveMappingFields['relationship_type_id'] = $id;
852 $saveMappingFields['relationship_direction'] = "{$first}_{$second}";
856 return $saveMappingFields;
860 * Load saved mapping.
862 * @param $mappingLocation
865 * @param $mappingName
866 * @param $mapperFields
867 * @param $mappingContactType
868 * @param $mappingRelation
869 * @param array $specialFields
870 * @param $mappingPhoneType
872 * @param array $defaults
873 * @param array $noneArray
875 * @param $mappingImProvider
876 * @param $mappingOperator
877 * @param $mappingValue
881 protected static function loadSavedMapping($mappingLocation, int $x, int $i, $mappingName, $mapperFields, $mappingContactType, $mappingRelation, array $specialFields, $mappingPhoneType, array $defaults, array $noneArray, $mappingImProvider, $mappingOperator, $mappingValue) {
883 $locationId = $mappingLocation[$x][$i] ??
0;
884 if (isset($mappingName[$x][$i])) {
885 if (is_array($mapperFields[$mappingContactType[$x][$i]])) {
887 if (isset($mappingRelation[$x][$i])) {
888 $relLocationId = $mappingLocation[$x][$i] ??
0;
889 if (!$relLocationId && in_array($mappingName[$x][$i], $specialFields)) {
890 $relLocationId = " ";
893 $relPhoneType = $mappingPhoneType[$x][$i] ??
NULL;
895 $defaults["mapper[$x][$i]"] = [
896 $mappingContactType[$x][$i],
897 $mappingRelation[$x][$i],
900 $mappingName[$x][$i],
906 $noneArray[] = [$x, $i, 2];
908 if (!$phoneType && !$imProvider) {
909 $noneArray[] = [$x, $i, 3];
911 if (!$mappingName[$x][$i]) {
912 $noneArray[] = [$x, $i, 4];
914 if (!$relLocationId) {
915 $noneArray[] = [$x, $i, 5];
917 if (!$relPhoneType) {
918 $noneArray[] = [$x, $i, 6];
920 $noneArray[] = [$x, $i, 2];
923 $phoneType = $mappingPhoneType[$x][$i] ??
NULL;
924 $imProvider = $mappingImProvider[$x][$i] ??
NULL;
925 if (!$locationId && in_array($mappingName[$x][$i], $specialFields)) {
929 $defaults["mapper[$x][$i]"] = [
930 $mappingContactType[$x][$i],
931 $mappingName[$x][$i],
935 if (!$mappingName[$x][$i]) {
936 $noneArray[] = [$x, $i, 1];
939 $noneArray[] = [$x, $i, 2];
941 if (!$phoneType && !$imProvider) {
942 $noneArray[] = [$x, $i, 3];
945 $noneArray[] = [$x, $i, 4];
946 $noneArray[] = [$x, $i, 5];
947 $noneArray[] = [$x, $i, 6];
952 if (CRM_Utils_Array
::value($i, CRM_Utils_Array
::value($x, $mappingOperator))) {
953 $defaults["operator[$x][$i]"] = $mappingOperator[$x][$i] ??
NULL;
956 if (CRM_Utils_Array
::value($i, CRM_Utils_Array
::value($x, $mappingValue))) {
957 $defaults["value[$x][$i]"] = $mappingValue[$x][$i] ??
NULL;
961 return [$mappingName, $defaults, $noneArray, $jsSet];
965 * Function returns all custom fields with group title and
968 * @param int $relationshipTypeId
969 * Related relationship type id.
972 * all custom field titles
974 public function getRelationTypeCustomGroupData($relationshipTypeId) {
976 $customFields = CRM_Core_BAO_CustomField
::getFields('Relationship', NULL, NULL, $relationshipTypeId, NULL, NULL);
978 foreach ($customFields as $krelation => $vrelation) {
979 $groupTitle[$vrelation['label']] = $vrelation['groupTitle'] . '...' . $vrelation['label'];
985 * Function returns all Custom group Names.
987 * @param int $customfieldId
990 * @return null|string
991 * $customGroupName all custom group names
993 public static function getCustomGroupName($customfieldId) {
994 if ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($customfieldId)) {
995 $customGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $customFieldId, 'custom_group_id');
996 $customGroupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'title');
998 $customGroupName = CRM_Utils_String
::ellipsify($customGroupName, 13);
1000 return $customGroupName;
1005 * Function returns associated array of elements, that will be passed for search
1007 * @param array $params
1008 * Associated array of submitted values.
1010 * Row no of the fields.
1014 * formatted associated array of elements
1015 * @throws CRM_Core_Exception
1017 public static function formattedFields(&$params, $row = FALSE) {
1020 if (empty($params) ||
!isset($params['mapper'])) {
1024 $types = ['Individual', 'Organization', 'Household'];
1025 foreach ($params['mapper'] as $key => $value) {
1026 $contactType = NULL;
1027 foreach ($value as $k => $v) {
1028 if (in_array($v[0], $types)) {
1029 if ($contactType && $contactType != $v[0]) {
1030 throw new CRM_Core_Exception(ts("Cannot have two clauses with different types: %1, %2",
1031 [1 => $contactType, 2 => $v[0]]
1034 $contactType = $v[0];
1036 if (!empty($v['1'])) {
1038 $v2 = $v['2'] ??
NULL;
1039 if ($v2 && trim($v2)) {
1040 $fldName .= "-{$v[2]}";
1043 $v3 = $v['3'] ??
NULL;
1044 if ($v3 && trim($v3)) {
1045 $fldName .= "-{$v[3]}";
1048 $value = $params['value'][$key][$k];
1050 if ($v[0] == 'Contribution' && substr($fldName, 0, 7) != 'custom_'
1051 && substr($fldName, 0, 10) != 'financial_'
1052 && substr($fldName, 0, 8) != 'payment_') {
1053 if (substr($fldName, 0, 13) != 'contribution_') {
1054 $fldName = 'contribution_' . $fldName;
1058 // CRM-14983: verify if values are comma separated convert to array
1059 if (!is_array($value) && strstr($params['operator'][$key][$k], 'IN')) {
1060 $value = explode(',', $value);
1061 $value = [$params['operator'][$key][$k] => $value];
1063 // CRM-19081 Fix legacy StateProvince Field Values.
1064 // These derive from smart groups created using search builder under older
1065 // CiviCRM versions.
1066 if (!is_numeric($value) && $fldName == 'state_province') {
1067 $value = CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Address', 'state_province_id', $value);
1073 $params['operator'][$key][$k],
1082 $params['operator'][$key][$k],
1101 //add sortByCharacter values
1102 if (isset($params['sortByCharacter'])) {
1106 $params['sortByCharacter'],
1115 * @param array $params
1119 public static function &returnProperties(&$params) {
1121 'contact_type' => 1,
1122 'contact_sub_type' => 1,
1126 if (empty($params) ||
empty($params['mapper'])) {
1130 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
1131 foreach ($params['mapper'] as $key => $value) {
1132 foreach ($value as $k => $v) {
1134 if ($v[1] == 'groups' ||
$v[1] == 'tags') {
1138 if (isset($v[2]) && is_numeric($v[2])) {
1139 if (!array_key_exists('location', $fields)) {
1140 $fields['location'] = [];
1143 // make sure that we have a location fields and a location type for this
1144 $locationName = $locationTypes[$v[2]];
1145 if (!array_key_exists($locationName, $fields['location'])) {
1146 $fields['location'][$locationName] = [];
1147 $fields['location'][$locationName]['location_type'] = $v[2];
1150 if ($v[1] == 'phone' ||
$v[1] == 'email' ||
$v[1] == 'im') {
1151 // phone type handling
1153 $fields['location'][$locationName][$v[1] . "-" . $v[3]] = 1;
1156 $fields['location'][$locationName][$v[1]] = 1;
1160 $fields['location'][$locationName][$v[1]] = 1;
1174 * Save the mapping field info for search builder / export given the formvalues
1176 * @param array $params
1177 * Asscociated array of formvalues.
1178 * @param int $mappingId
1183 public static function saveMappingFields($params, $mappingId) {
1184 //delete mapping fields records for existing mapping
1185 $mappingFields = new CRM_Core_DAO_MappingField();
1186 $mappingFields->mapping_id
= $mappingId;
1187 $mappingFields->delete();
1189 if (empty($params['mapper'])) {
1193 //save record in mapping field table
1194 foreach ($params['mapper'] as $key => $value) {
1196 foreach ($value as $k => $v) {
1198 if (!empty($v['1'])) {
1199 $saveMappingParams = self
::getMappingParams(
1201 'mapping_id' => $mappingId,
1203 'operator' => $params['operator'][$key][$k] ??
NULL,
1204 'value' => $params['value'][$key][$k] ??
NULL,
1205 'column_number' => $colCnt,
1207 $saveMappingField = new CRM_Core_DAO_MappingField();
1208 $saveMappingField->copyValues($saveMappingParams);
1209 $saveMappingField->save();