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
implements \Civi\Core\HookInterface
{
20 * Retrieve DB object and copy to defaults array.
22 * @param array $params
23 * Array of criteria values.
24 * @param array $defaults
25 * Array to be populated with found values.
28 * The DAO object, if found.
32 public static function retrieve($params, &$defaults) {
33 return self
::commonRetrieve(self
::class, $params, $defaults);
44 public static function del($id) {
45 return (bool) static::deleteRecord(['id' => $id]);
49 * Takes an associative array and creates a contact object.
51 * The function extract all the params it needs to initialize the create a
52 * contact object. the params array could contain additional unused name/value
55 * @param array $params
56 * An array of name/value pairs.
59 * CRM_Core_DAO_Mapper object on success, otherwise NULL
61 public static function add($params) {
62 $mapping = new CRM_Core_DAO_Mapping();
63 $mapping->copyValues($params);
70 * Get the list of mappings for a select or select2 element.
72 * @param string $mappingType
74 * @param bool $select2
78 * Array of mapping names, keyed by id.
80 public static function getMappings($mappingType, $select2 = FALSE) {
81 $result = civicrm_api3('Mapping', 'get', [
82 'mapping_type_id' => $mappingType,
83 'return' => ['name', 'description'],
91 foreach ($result['values'] as $id => $value) {
93 $item = ['id' => $id, 'text' => $value['name']];
94 if (!empty($value['description'])) {
95 $item['description'] = $value['description'];
100 $mapping[$id] = $value['name'];
107 * Get the mappings array, creating if it does not exist.
109 * @param string $mappingType
113 * Array of mapping names, keyed by id.
115 * @throws \CiviCRM_API3_Exception
117 public static function getCreateMappingValues($mappingType) {
119 return CRM_Core_BAO_Mapping
::getMappings($mappingType);
121 catch (CiviCRM_API3_Exception
$e) {
122 // Having a valid mapping_type_id is now enforced. However, rather than error let's
123 // add it. This is required for Multi value which could be done by upgrade script, but
124 // it feels like there could be other instances so this is safer.
125 $errorParams = $e->getExtraParams();
126 if ($errorParams['error_field'] === 'mapping_type_id') {
127 $mappingValues = civicrm_api3('Mapping', 'getoptions', ['field' => 'mapping_type_id']);
128 civicrm_api3('OptionValue', 'create', [
129 'option_group_id' => 'mapping_type',
130 'label' => $mappingType,
131 'name' => $mappingType,
132 'value' => max(array_keys($mappingValues['values'])) +
1,
135 return CRM_Core_BAO_Mapping
::getMappings($mappingType);
142 * Get the mapping fields.
144 * @param int $mappingId
147 * @param bool $addPrimary
148 * Add the key 'Primary' when the field is a location field AND there is
149 * no location type (meaning Primary)?
152 * array of mapping fields
154 public static function getMappingFields($mappingId, $addPrimary = FALSE) {
155 //mapping is to be loaded from database
156 $mapping = new CRM_Core_DAO_MappingField();
157 $mapping->mapping_id
= $mappingId;
158 $mapping->orderBy('column_number');
161 $mappingName = $mappingLocation = $mappingContactType = $mappingPhoneType = [];
162 $mappingImProvider = $mappingRelation = $mappingOperator = $mappingValue = $mappingWebsiteType = [];
163 while ($mapping->fetch()) {
164 $mappingName[$mapping->grouping
][$mapping->column_number
] = $mapping->name
;
165 $mappingContactType[$mapping->grouping
][$mapping->column_number
] = $mapping->contact_type
;
167 if (!empty($mapping->location_type_id
)) {
168 $mappingLocation[$mapping->grouping
][$mapping->column_number
] = $mapping->location_type_id
;
170 elseif ($addPrimary) {
171 if (CRM_Contact_BAO_Contact
::isFieldHasLocationType($mapping->name
)) {
172 $mappingLocation[$mapping->grouping
][$mapping->column_number
] = ts('Primary');
175 $mappingLocation[$mapping->grouping
][$mapping->column_number
] = NULL;
179 if (!empty($mapping->phone_type_id
)) {
180 $mappingPhoneType[$mapping->grouping
][$mapping->column_number
] = $mapping->phone_type_id
;
183 // get IM service provider type id from mapping fields
184 if (!empty($mapping->im_provider_id
)) {
185 $mappingImProvider[$mapping->grouping
][$mapping->column_number
] = $mapping->im_provider_id
;
188 if (!empty($mapping->website_type_id
)) {
189 $mappingWebsiteType[$mapping->grouping
][$mapping->column_number
] = $mapping->website_type_id
;
192 if (!empty($mapping->relationship_type_id
)) {
193 $mappingRelation[$mapping->grouping
][$mapping->column_number
] = "{$mapping->relationship_type_id}_{$mapping->relationship_direction}";
196 if (!empty($mapping->operator
)) {
197 $mappingOperator[$mapping->grouping
][$mapping->column_number
] = $mapping->operator
;
200 if (isset($mapping->value
)) {
201 $mappingValue[$mapping->grouping
][$mapping->column_number
] = $mapping->value
;
219 * Get un-indexed array of the field values for the given mapping id.
221 * For example if passing a mapping ID & name the returned array would look like
222 * ['First field name', 'second field name']
224 * @param int $mappingID
225 * @param string $fieldName
228 * @throws \CiviCRM_API3_Exception
230 public static function getMappingFieldValues($mappingID, $fieldName) {
231 return array_merge(CRM_Utils_Array
::collect($fieldName, civicrm_api3('MappingField', 'get', ['mapping_id' => $mappingID, 'return' => $fieldName])['values']));
235 * Check Duplicate Mapping Name.
237 * @param string $nameField
239 * @param string $mapTypeId
244 public static function checkMapping($nameField, $mapTypeId) {
245 $mapping = new CRM_Core_DAO_Mapping();
246 $mapping->name
= $nameField;
247 $mapping->mapping_type_id
= $mapTypeId;
248 return (bool) $mapping->find(TRUE);
252 * Function returns associated array of elements, that will be passed for search.
254 * @param int $smartGroupId
258 * associated array of elements
260 public static function getFormattedFields($smartGroupId) {
263 //get the fields from mapping table
264 $dao = new CRM_Core_DAO_MappingField();
265 $dao->mapping_id
= $smartGroupId;
267 while ($dao->fetch()) {
268 $fldName = $dao->name
;
269 if ($dao->location_type_id
) {
270 $fldName .= "-{$dao->location_type_id}";
272 if ($dao->phone_type
) {
273 $fldName .= "-{$dao->phone_type}";
275 $returnFields[$fldName]['value'] = $dao->value
;
276 $returnFields[$fldName]['op'] = $dao->operator
;
277 $returnFields[$fldName]['grouping'] = $dao->grouping
;
279 return $returnFields;
283 * Build the mapping form for Search Builder.
285 * @param CRM_Core_Form $form
286 * @param int $mappingId
287 * @param int $columnNo
288 * @param int $blockCount
289 * (no of blocks shown).
290 * @param int $exportMode
292 public static function buildMappingForm(&$form, $mappingId, $columnNo, $blockCount, $exportMode = NULL) {
294 $hasLocationTypes = [];
295 $hasRelationTypes = [];
297 $columnCount = $columnNo;
298 $form->addElement('xbutton', 'addBlock', ts('Also include contacts where'),
301 'class' => 'submit-link',
306 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypes();
307 $fields = self
::getBasicFields('Search Builder');
309 // Unset groups, tags, notes for component export
310 if ($exportMode != CRM_Export_Form_Select
::CONTACT_EXPORT
) {
311 foreach (array_keys($fields) as $type) {
312 CRM_Utils_Array
::remove($fields[$type], 'groups', 'tags', 'notes');
316 // Build the common contact fields array.
317 $fields['Contact'] = [];
318 foreach ($fields[$contactTypes[0]] as $key => $value) {
319 // If a field exists across all contact types, move it to the "Contact" selector
321 foreach ($contactTypes as $type) {
322 if (!isset($fields[$type][$key])) {
323 $ubiquitious = FALSE;
327 $fields['Contact'][$key] = $value;
328 foreach ($contactTypes as $type) {
329 unset($fields[$type][$key]);
333 if (array_key_exists('note', $fields['Contact'])) {
334 $noteTitle = $fields['Contact']['note']['title'];
335 $fields['Contact']['note']['title'] = $noteTitle . ': ' . ts('Body and Subject');
336 $fields['Contact']['note_body'] = ['title' => $noteTitle . ': ' . ts('Body Only'), 'name' => 'note_body'];
337 $fields['Contact']['note_subject'] = [
338 'title' => $noteTitle . ': ' . ts('Subject Only'),
339 'name' => 'note_subject',
343 // add component fields
344 $compArray = self
::addComponentFields($fields, 'Search Builder', $exportMode);
346 foreach ($fields as $key => $value) {
348 foreach ($value as $key1 => $value1) {
349 //CRM-2676, replacing the conflict for same custom field name from different custom group.
350 $customGroupName = self
::getCustomGroupName($key1);
352 if ($customGroupName) {
353 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $customGroupName . ': ' . $value1['title'];
356 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $value1['title'];
358 if (isset($value1['hasLocationType'])) {
359 $hasLocationTypes[$key][$key1] = $value1['hasLocationType'];
362 if (isset($value1['hasRelationType'])) {
363 $hasRelationTypes[$key][$key1] = $value1['hasRelationType'];
364 unset($relatedMapperFields[$key][$key1]);
368 if (isset($relatedMapperFields[$key]['related'])) {
369 unset($relatedMapperFields[$key]['related']);
373 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
375 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
377 // FIXME: dirty hack to make the default option show up first. This
378 // avoids a mozilla browser bug with defaults on dynamically constructed
380 if ($defaultLocationType) {
381 $defaultLocation = $locationTypes[$defaultLocationType->id
];
382 unset($locationTypes[$defaultLocationType->id
]);
383 $locationTypes = [$defaultLocationType->id
=> $defaultLocation] +
$locationTypes;
386 $locationTypes = [' ' => ts('Primary')] +
$locationTypes;
388 // since we need a hierarchical list to display contact types & subtypes,
389 // this is what we going to display in first selector
390 $contactTypeSelect = CRM_Contact_BAO_ContactType
::getSelectElements(FALSE, FALSE);
391 $contactTypeSelect = ['Contact' => ts('Contacts')] +
$contactTypeSelect;
393 $sel1 = ['' => ts('- select record type -')] +
$contactTypeSelect +
$compArray;
395 foreach ($sel1 as $key => $sel) {
397 // sort everything BUT the contactType which is sorted separately by
398 // an initial commit of CRM-13278 (check ksort above)
399 if (!in_array($key, $contactTypes)) {
400 asort($mapperFields[$key]);
402 $sel2[$key] = ['' => ts('- select field -')] +
$mapperFields[$key];
408 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
409 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
412 foreach ($sel1 as $k => $sel) {
414 foreach ($locationTypes as $key => $value) {
415 if (trim($key) != '') {
416 $sel4[$k]['phone'][$key] = &$phoneTypes;
417 $sel4[$k]['im'][$key] = &$imProviders;
423 foreach ($sel1 as $k => $sel) {
425 foreach ($mapperFields[$k] as $key => $value) {
426 if (isset($hasLocationTypes[$k][$key])) {
427 $sel3[$k][$key] = $locationTypes;
436 // Array for core fields and relationship custom data
437 $relationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
439 //special fields that have location, hack for primary location
442 'supplemental_address_1',
443 'supplemental_address_2',
444 'supplemental_address_3',
447 'postal_code_suffix',
457 if (isset($mappingId)) {
458 list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider,
459 $mappingRelation, $mappingOperator, $mappingValue
460 ) = CRM_Core_BAO_Mapping
::getMappingFields($mappingId);
462 $blkCnt = count($mappingName);
463 if ($blkCnt >= $blockCount) {
464 $blockCount = $blkCnt +
1;
466 for ($x = 1; $x < $blockCount; $x++
) {
467 if (isset($mappingName[$x])) {
468 $colCnt = count($mappingName[$x]);
469 if ($colCnt >= $columnCount[$x]) {
470 $columnCount[$x] = $colCnt;
476 $form->_blockCount
= $blockCount;
477 $form->_columnCount
= $columnCount;
479 $form->set('blockCount', $form->_blockCount
);
480 $form->set('columnCount', $form->_columnCount
);
482 $defaults = $noneArray = $nullArray = [];
484 for ($x = 1; $x < $blockCount; $x++
) {
486 for ($i = 0; $i < $columnCount[$x]; $i++
) {
488 $sel = &$form->addElement('hierselect', "mapper[$x][$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
491 if (isset($mappingId)) {
492 list($mappingName, $defaults, $noneArray, $jsSet) = self
::loadSavedMapping($mappingLocation, $x, $i, $mappingName, $mapperFields, $mappingContactType, $mappingRelation, $specialFields, $mappingPhoneType, $defaults, $noneArray, $mappingImProvider, $mappingOperator, $mappingValue);
494 //Fix for Search Builder
497 $formValues = $form->exportValues();
499 if (empty($formValues)) {
500 // Incremented length for third select box(relationship type)
501 for ($k = 1; $k < $j; $k++
) {
502 $noneArray[] = [$x, $i, $k];
506 if (!empty($formValues['mapper'][$x])) {
507 foreach ($formValues['mapper'][$x] as $value) {
508 for ($k = 1; $k < $j; $k++
) {
509 if (!isset($formValues['mapper'][$x][$i][$k]) ||
510 (!$formValues['mapper'][$x][$i][$k])
512 $noneArray[] = [$x, $i, $k];
515 $nullArray[] = [$x, $i, $k];
521 for ($k = 1; $k < $j; $k++
) {
522 $noneArray[] = [$x, $i, $k];
527 //Fix for Search Builder
528 $sel->setOptions([$sel1, $sel2, $sel3, $sel4]);
530 //CRM -2292, restricted array set
531 $operatorArray = ['' => ts('-operator-')] + CRM_Core_SelectValues
::getSearchBuilderOperators();
533 $form->add('select', "operator[$x][$i]", '', $operatorArray);
534 $form->add('text', "value[$x][$i]", '');
537 $form->addElement('xbutton', "addMore[$x]", ts('Another search field'), [
539 'class' => 'submit-link',
545 $js = "<script type='text/javascript'>\n";
546 $formName = "document.Builder";
547 if (!empty($nullArray)) {
548 $js .= "var nullArray = [";
551 foreach ($nullArray as $element) {
552 $key = "{$element[0]}, {$element[1]}, {$element[2]}";
553 if (!isset($seen[$key])) {
554 $elements[] = "[$key]";
558 $js .= implode(', ', $elements);
561 for (var i=0;i<nullArray.length;i++) {
562 if ( {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'] ) {
563 {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'].style.display = '';
568 if (!empty($noneArray)) {
569 $js .= "var noneArray = [";
572 foreach ($noneArray as $element) {
573 $key = "{$element[0]}, {$element[1]}, {$element[2]}";
574 if (!isset($seen[$key])) {
575 $elements[] = "[$key]";
579 $js .= implode(', ', $elements);
582 for (var i=0;i<noneArray.length;i++) {
583 if ( {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'] ) {
584 {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'].style.display = 'none';
589 $js .= "</script>\n";
591 $form->assign('initHideBoxes', $js);
592 $form->assign('columnCount', $columnCount);
593 $form->assign('blockCount', $blockCount);
594 $form->setDefaults($defaults);
596 $form->setDefaultAction('refresh');
600 * @param string $mappingType
603 public static function getBasicFields($mappingType) {
604 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypes();
606 foreach ($contactTypes as $contactType) {
607 if ($mappingType == 'Search Builder') {
608 // Get multiple custom group fields in this context
609 $contactFields = CRM_Contact_BAO_Contact
::exportableFields($contactType, FALSE, FALSE, FALSE, TRUE);
612 $contactFields = CRM_Contact_BAO_Contact
::exportableFields($contactType, FALSE, TRUE);
614 // It's unclear when we would want this but.... see
615 // https://lab.civicrm.org/dev/core/-/issues/3069 for when we don't....
616 $contactFields = array_merge($contactFields, CRM_Contact_BAO_Query_Hook
::singleton()
617 ->getContactFields());
619 // Exclude the address options disabled in the Address Settings
620 $fields[$contactType] = CRM_Core_BAO_Address
::validateAddressOptions($contactFields);
621 ksort($fields[$contactType]);
622 if ($mappingType == 'Export') {
624 $relationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, $contactType);
625 asort($relationshipTypes);
627 foreach ($relationshipTypes as $key => $var) {
628 list($type) = explode('_', $key);
630 $relationships[$key]['title'] = $var;
631 $relationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
632 $relationships[$key]['export'] = TRUE;
633 $relationships[$key]['relationship_type_id'] = $type;
634 $relationships[$key]['related'] = TRUE;
635 $relationships[$key]['hasRelationType'] = 1;
638 if (!empty($relationships)) {
639 $fields[$contactType] = array_merge($fields[$contactType],
640 ['related' => ['title' => ts('- related contact info -')]],
644 if (!empty($fields[$contactType]['state_province']) && empty($fields[$contactType]['state_province_name'])) {
645 $fields[$contactType]['state_province_name'] = $fields[$contactType]['state_province'];
646 $fields[$contactType]['state_province_name']['title'] = ts('State/Province Name');
647 $fields[$contactType]['state_province']['title'] = ts('State/Province Abbreviation');
652 // Get the current employer for mapping.
653 if ($mappingType == 'Export') {
654 $fields['Individual']['current_employer_id']['title'] = ts('Current Employer ID');
657 // Contact Sub Type For export
658 $subTypes = CRM_Contact_BAO_ContactType
::subTypeInfo();
659 foreach ($subTypes as $subType => $info) {
660 //adding subtype specific relationships CRM-5256
661 $csRelationships = [];
663 if ($mappingType == 'Export') {
664 $subTypeRelationshipTypes
665 = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, $info['parent'],
666 FALSE, 'label', TRUE, $subType);
668 foreach ($subTypeRelationshipTypes as $key => $var) {
669 if (!array_key_exists($key, $fields[$info['parent']])) {
670 list($type) = explode('_', $key);
672 $csRelationships[$key]['title'] = $var;
673 $csRelationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
674 $csRelationships[$key]['export'] = TRUE;
675 $csRelationships[$key]['relationship_type_id'] = $type;
676 $csRelationships[$key]['related'] = TRUE;
677 $csRelationships[$key]['hasRelationType'] = 1;
682 $fields[$subType] = $fields[$info['parent']] +
$csRelationships;
684 //custom fields for sub type
685 $subTypeFields = CRM_Core_BAO_CustomField
::getFieldsForImport($subType);
686 $fields[$subType] +
= $subTypeFields;
693 * Adds component fields to the export fields array; returns list of components.
695 * @param array $fields
696 * @param string $mappingType
697 * @param int $exportMode
700 public static function addComponentFields(&$fields, $mappingType, $exportMode) {
703 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
)) {
704 if (CRM_Core_Permission
::access('CiviContribute')) {
705 $fields['Contribution'] = CRM_Core_DAO
::getExportableFieldsWithPseudoConstants('CRM_Contribute_BAO_Contribution');
706 unset($fields['Contribution']['contribution_contact_id']);
707 $compArray['Contribution'] = ts('Contribution');
711 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
)) {
712 if (CRM_Core_Permission
::access('CiviEvent')) {
713 $fields['Participant'] = CRM_Event_BAO_Participant
::exportableFields();
714 //get the component payment fields
715 // @todo - review this - inconsistent with other entities & hacky.
716 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
717 $componentPaymentFields = [];
719 'componentPaymentField_total_amount' => ts('Total Amount'),
720 'componentPaymentField_contribution_status' => ts('Contribution Status'),
721 'componentPaymentField_received_date' => ts('Date Received'),
722 'componentPaymentField_payment_instrument' => ts('Payment Method'),
723 'componentPaymentField_transaction_id' => ts('Transaction ID'),
724 ] as $payField => $payTitle) {
725 $componentPaymentFields[$payField] = ['title' => $payTitle];
727 $fields['Participant'] = array_merge($fields['Participant'], $componentPaymentFields);
730 $compArray['Participant'] = ts('Participant');
734 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
)) {
735 if (CRM_Core_Permission
::access('CiviMember')) {
736 $fields['Membership'] = CRM_Member_BAO_Membership
::getMembershipFields($exportMode);
737 unset($fields['Membership']['membership_contact_id']);
738 $compArray['Membership'] = ts('Membership');
742 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
)) {
743 if (CRM_Core_Permission
::access('CiviPledge')) {
744 $fields['Pledge'] = CRM_Pledge_BAO_Pledge
::exportableFields();
745 unset($fields['Pledge']['pledge_contact_id']);
746 $compArray['Pledge'] = ts('Pledge');
750 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
)) {
751 if (CRM_Core_Permission
::access('CiviCase')) {
752 $fields['Case'] = CRM_Case_BAO_Case
::exportableFields();
753 $compArray['Case'] = ts('Case');
755 $fields['Activity'] = CRM_Activity_BAO_Activity
::exportableFields('Case');
756 $compArray['Activity'] = ts('Case Activity');
758 unset($fields['Case']['case_contact_id']);
761 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
)) {
762 if (method_exists('CRM_Grant_BAO_Grant', 'exportableFields') && CRM_Core_Permission
::check('access CiviGrant')) {
763 $fields['Grant'] = CRM_Grant_BAO_Grant
::exportableFields();
764 unset($fields['Grant']['grant_contact_id']);
765 if ($mappingType == 'Search Builder') {
766 unset($fields['Grant']['grant_type_id']);
768 $compArray['Grant'] = ts('Grant');
772 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
)) {
773 $fields['Activity'] = CRM_Activity_BAO_Activity
::exportableFields('Activity');
774 $compArray['Activity'] = ts('Activity');
781 * Get the parameters for a mapping field in a saveable format from the quickform mapping format.
783 * @param array $defaults
788 public static function getMappingParams($defaults, $v) {
789 $locationTypeId = NULL;
790 $saveMappingFields = $defaults;
792 $saveMappingFields['name'] = $v['1'] ??
NULL;
793 $saveMappingFields['contact_type'] = $v['0'] ??
NULL;
794 $locationId = $v['2'] ??
NULL;
795 $saveMappingFields['location_type_id'] = is_numeric($locationId) ?
$locationId : NULL;
797 if ($v[1] == 'phone') {
798 $saveMappingFields['phone_type_id'] = $v['3'] ??
NULL;
800 elseif ($v[1] == 'im') {
801 $saveMappingFields['im_provider_id'] = $v['3'] ??
NULL;
804 // Handle mapping for 'related contact' fields
805 if (count(explode('_', CRM_Utils_Array
::value('1', $v))) > 2) {
806 list($id, $first, $second) = explode('_', CRM_Utils_Array
::value('1', $v));
807 if (($first == 'a' && $second == 'b') ||
($first == 'b' && $second == 'a')) {
809 if (!empty($v['2'])) {
810 $saveMappingFields['name'] = $v['2'] ??
NULL;
812 elseif (!empty($v['4'])) {
813 $saveMappingFields['name'] = $v['4'] ??
NULL;
816 if (is_numeric(CRM_Utils_Array
::value('3', $v))) {
817 $locationTypeId = $v['3'] ??
NULL;
819 elseif (is_numeric(CRM_Utils_Array
::value('5', $v))) {
820 $locationTypeId = $v['5'] ??
NULL;
823 if (is_numeric(CRM_Utils_Array
::value('4', $v))) {
824 if ($saveMappingFields['name'] === 'im') {
825 $saveMappingFields['im_provider_id'] = $v[4];
828 $saveMappingFields['phone_type_id'] = $v['4'] ??
NULL;
831 elseif (is_numeric(CRM_Utils_Array
::value('6', $v))) {
832 $saveMappingFields['phone_type_id'] = $v['6'] ??
NULL;
835 $saveMappingFields['location_type_id'] = is_numeric($locationTypeId) ?
$locationTypeId : NULL;
836 $saveMappingFields['relationship_type_id'] = $id;
837 $saveMappingFields['relationship_direction'] = "{$first}_{$second}";
841 return $saveMappingFields;
845 * Load saved mapping.
847 * @param $mappingLocation
850 * @param $mappingName
851 * @param $mapperFields
852 * @param $mappingContactType
853 * @param $mappingRelation
854 * @param array $specialFields
855 * @param $mappingPhoneType
857 * @param array $defaults
858 * @param array $noneArray
860 * @param $mappingImProvider
861 * @param $mappingOperator
862 * @param $mappingValue
866 protected static function loadSavedMapping($mappingLocation, int $x, int $i, $mappingName, $mapperFields, $mappingContactType, $mappingRelation, array $specialFields, $mappingPhoneType, array $defaults, array $noneArray, $mappingImProvider, $mappingOperator, $mappingValue) {
868 $locationId = $mappingLocation[$x][$i] ??
0;
869 if (isset($mappingName[$x][$i])) {
870 if (is_array($mapperFields[$mappingContactType[$x][$i]])) {
872 if (isset($mappingRelation[$x][$i])) {
873 $relLocationId = $mappingLocation[$x][$i] ??
0;
874 if (!$relLocationId && in_array($mappingName[$x][$i], $specialFields)) {
875 $relLocationId = " ";
878 $relPhoneType = $mappingPhoneType[$x][$i] ??
NULL;
880 $defaults["mapper[$x][$i]"] = [
881 $mappingContactType[$x][$i],
882 $mappingRelation[$x][$i],
885 $mappingName[$x][$i],
891 $noneArray[] = [$x, $i, 2];
893 if (!$phoneType && !$imProvider) {
894 $noneArray[] = [$x, $i, 3];
896 if (!$mappingName[$x][$i]) {
897 $noneArray[] = [$x, $i, 4];
899 if (!$relLocationId) {
900 $noneArray[] = [$x, $i, 5];
902 if (!$relPhoneType) {
903 $noneArray[] = [$x, $i, 6];
905 $noneArray[] = [$x, $i, 2];
908 $phoneType = $mappingPhoneType[$x][$i] ??
NULL;
909 $imProvider = $mappingImProvider[$x][$i] ??
NULL;
910 if (!$locationId && in_array($mappingName[$x][$i], $specialFields)) {
914 $defaults["mapper[$x][$i]"] = [
915 $mappingContactType[$x][$i],
916 $mappingName[$x][$i],
920 if (!$mappingName[$x][$i]) {
921 $noneArray[] = [$x, $i, 1];
924 $noneArray[] = [$x, $i, 2];
926 if (!$phoneType && !$imProvider) {
927 $noneArray[] = [$x, $i, 3];
930 $noneArray[] = [$x, $i, 4];
931 $noneArray[] = [$x, $i, 5];
932 $noneArray[] = [$x, $i, 6];
937 if (CRM_Utils_Array
::value($i, CRM_Utils_Array
::value($x, $mappingOperator))) {
938 $defaults["operator[$x][$i]"] = $mappingOperator[$x][$i] ??
NULL;
941 if (isset($mappingValue[$x][$i])) {
942 $defaults["value[$x][$i]"] = $mappingValue[$x][$i] ??
NULL;
946 return [$mappingName, $defaults, $noneArray, $jsSet];
950 * Function returns all custom fields with group title and
953 * @param int $relationshipTypeId
954 * Related relationship type id.
957 * all custom field titles
959 public function getRelationTypeCustomGroupData($relationshipTypeId) {
961 $customFields = CRM_Core_BAO_CustomField
::getFields('Relationship', NULL, NULL, $relationshipTypeId, NULL, NULL);
963 foreach ($customFields as $krelation => $vrelation) {
964 $groupTitle[$vrelation['label']] = $vrelation['groupTitle'] . '...' . $vrelation['label'];
970 * Function returns all Custom group Names.
972 * @param int $customfieldId
975 * @return null|string
976 * $customGroupName all custom group names
978 public static function getCustomGroupName($customfieldId) {
979 if ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($customfieldId)) {
980 $customGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $customFieldId, 'custom_group_id');
981 $customGroupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'title');
983 $customGroupName = CRM_Utils_String
::ellipsify($customGroupName, 13);
985 return $customGroupName;
990 * Function returns associated array of elements, that will be passed for search
992 * @param array $params
993 * Associated array of submitted values.
995 * Row no of the fields.
999 * formatted associated array of elements
1000 * @throws CRM_Core_Exception
1002 public static function formattedFields(&$params, $row = FALSE) {
1005 if (empty($params) ||
!isset($params['mapper'])) {
1009 $types = CRM_Contact_BAO_ContactType
::basicTypes(TRUE);
1010 foreach ($params['mapper'] as $key => $value) {
1011 $contactType = NULL;
1012 foreach ($value as $k => $v) {
1013 if (in_array($v[0], $types, TRUE)) {
1014 if ($contactType && $contactType != $v[0]) {
1015 throw new CRM_Core_Exception(ts("Cannot have two clauses with different types: %1, %2",
1016 [1 => $contactType, 2 => $v[0]]
1019 $contactType = $v[0];
1021 if (!empty($v['1'])) {
1023 $v2 = $v['2'] ??
NULL;
1024 if ($v2 && trim($v2)) {
1025 $fldName .= "-{$v[2]}";
1028 $v3 = $v['3'] ??
NULL;
1029 if ($v3 && trim($v3)) {
1030 $fldName .= "-{$v[3]}";
1033 $value = $params['value'][$key][$k];
1035 if ($v[0] == 'Contribution' && substr($fldName, 0, 7) != 'custom_'
1036 && substr($fldName, 0, 10) != 'financial_'
1037 && substr($fldName, 0, 8) != 'payment_') {
1038 if (substr($fldName, 0, 13) != 'contribution_') {
1039 $fldName = 'contribution_' . $fldName;
1043 // CRM-14983: verify if values are comma separated convert to array
1044 if (!is_array($value) && strstr($params['operator'][$key][$k], 'IN')) {
1045 $value = explode(',', $value);
1046 $value = [$params['operator'][$key][$k] => $value];
1048 // CRM-19081 Fix legacy StateProvince Field Values.
1049 // These derive from smart groups created using search builder under older
1050 // CiviCRM versions.
1051 if ($fldName == 'state_province' && !is_numeric($value) && !is_array($value)) {
1052 $value = CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Address', 'state_province_id', $value);
1058 $params['operator'][$key][$k],
1067 $params['operator'][$key][$k],
1086 //add sortByCharacter values
1087 if (isset($params['sortByCharacter'])) {
1091 $params['sortByCharacter'],
1100 * @param array $params
1104 public static function &returnProperties(&$params) {
1106 'contact_type' => 1,
1107 'contact_sub_type' => 1,
1111 if (empty($params) ||
empty($params['mapper'])) {
1115 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
1116 foreach ($params['mapper'] as $key => $value) {
1117 foreach ($value as $k => $v) {
1119 if ($v[1] == 'groups' ||
$v[1] == 'tags') {
1123 if (isset($v[2]) && is_numeric($v[2])) {
1124 if (!array_key_exists('location', $fields)) {
1125 $fields['location'] = [];
1128 // make sure that we have a location fields and a location type for this
1129 $locationName = $locationTypes[$v[2]];
1130 if (!array_key_exists($locationName, $fields['location'])) {
1131 $fields['location'][$locationName] = [];
1132 $fields['location'][$locationName]['location_type'] = $v[2];
1135 if ($v[1] == 'phone' ||
$v[1] == 'email' ||
$v[1] == 'im') {
1136 // phone type handling
1138 $fields['location'][$locationName][$v[1] . "-" . $v[3]] = 1;
1141 $fields['location'][$locationName][$v[1]] = 1;
1145 $fields['location'][$locationName][$v[1]] = 1;
1159 * Save the mapping field info for search builder / export given the formvalues
1161 * @param array $params
1162 * Asscociated array of formvalues.
1163 * @param int $mappingId
1168 public static function saveMappingFields($params, $mappingId) {
1169 //delete mapping fields records for existing mapping
1170 $mappingFields = new CRM_Core_DAO_MappingField();
1171 $mappingFields->mapping_id
= $mappingId;
1172 $mappingFields->delete();
1174 if (empty($params['mapper'])) {
1178 //save record in mapping field table
1179 foreach ($params['mapper'] as $key => $value) {
1181 foreach ($value as $k => $v) {
1183 if (!empty($v['1'])) {
1184 $saveMappingParams = self
::getMappingParams(
1186 'mapping_id' => $mappingId,
1188 'operator' => $params['operator'][$key][$k] ??
NULL,
1189 'value' => $params['value'][$key][$k] ??
NULL,
1190 'column_number' => $colCnt,
1192 $saveMappingField = new CRM_Core_DAO_MappingField();
1193 $saveMappingField->copyValues($saveMappingParams);
1194 $saveMappingField->save();
1202 * Remove references to a specific field from save Mappings
1203 * @param string $fieldName
1205 public static function removeFieldFromMapping($fieldName): void
{
1206 $mappingField = new CRM_Core_DAO_MappingField();
1207 $mappingField->name
= $fieldName;
1208 $mappingField->delete();
1212 * Callback for hook_civicrm_pre().
1213 * @param \Civi\Core\Event\PreEvent $event
1214 * @throws CRM_Core_Exception
1216 public static function on_hook_civicrm_pre(\Civi\Core\Event\PreEvent
$event) {
1217 if ($event->action
=== 'delete' && $event->entity
=== 'RelationshipType') {
1218 // CRM-3323 - Delete mappingField records when deleting relationship type
1219 \Civi\Api4\MappingField
::delete(FALSE)
1220 ->addWhere('relationship_type_id', '=', $event->id
)